Stomp and SockJs in a React Native



有人能在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:

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

onError:

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

最新更新