gpt4 book ai didi

reactjs - React Native 中的 Stomp 和 SockJs

转载 作者:行者123 更新时间:2023-12-03 08:19:33 25 4
gpt4 key购买 nike

有人可以在 React Native 项目中提供 Stomp + SocketJS 的成功实现吗?只是如何连接和使用它

最佳答案

以下是最重要的部分:

连接:

connect = (userId) => {
if (userId) {
var socket = new SockJS("http://localhost:1981/ws");
stompClient = Stomp.over(socket);

stompClient.connect({}, this.onConnected, this.onError);

}
}

OnConnected 您可以订阅或按照您的意愿在第一步中完成!:

onConnected = () => {
console.log("onConnected");
// Subscribe to the Public Topic
stompClient.subscribe("/topic/public", this.onMessageReceived);

// Tell your username to the server
stompClient.send(
"/api/chat/addUser/1",
{},
JSON.stringify({ sender: "Ali", type: "JOIN" })
);
}

收到消息:

onMessageReceived = (payload) => {
console.log("onMessageReceived");
var message = JSON.parse(payload.body);
}

错误:

onError = (error) => {
this.setState({
error:
"Could not connect you to the Chat Room Server. Please refresh this page and try again!",
});
};

发送消息:

sendMessage = (msg) => {
var messageContent = "test"
if (messageContent && stompClient) {
var chatMessage = {
sender: this.state.username,
content: "Heey there",
type: "CHAT",
};
stompClient.send(
"/api/chat/sendMessage/1",
{name: "Ali"},
JSON.stringify(chatMessage)
);
}
};

您可以随时返回以下文档:[1]:https://stomp-js.github.io/api-docs/latest/classes/Client.html#subscribe

关于reactjs - React Native 中的 Stomp 和 SockJs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68297252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com