Dal*_*ush 2 stomp websocket reactjs 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);
}
}
Run Code Online (Sandbox Code Playgroud)
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" })
);
}
Run Code Online (Sandbox Code Playgroud)
收到消息时:
onMessageReceived = (payload) => {
console.log("onMessageReceived");
var message = JSON.parse(payload.body);
}
Run Code Online (Sandbox Code Playgroud)
错误:
onError = (error) => {
this.setState({
error:
"Could not connect you to the Chat Room Server. Please refresh this page and try again!",
});
};
Run Code Online (Sandbox Code Playgroud)
发信息:
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)
);
}
};
Run Code Online (Sandbox Code Playgroud)
您可以随时返回以下文档:[1]:https ://stomp-js.github.io/api-docs/latest/classes/Client.html#subscribe
| 归档时间: |
|
| 查看次数: |
9266 次 |
| 最近记录: |