React Native 中的 Stomp 和 SockJs

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 = (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