reactjs - React Native 中的 Stomp 和 SockJs

标签 reactjs react-native websocket stomp

有人可以在 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/

相关文章:

javascript - componentDidMount 在 ref 回调之前被调用

javascript - 使用 find() 在对象中循环数组

javascript - 如何根据里面的组件调整 TouchableOpacity 的大小?

eclipse - 如何在 Eclipse 中使用 Tomcat 8?

ruby-on-rails - Faye 服务器日志记录

javascript - Node.js可以验证PHP用户的 session 吗?

javascript - Reactjs - Formik 表单不会在按下返回键时触发提交

javascript - 如何在 Facebook 的 FixedDataTable 中设置灵活的行高?

react-native - 为什么不生成设备 token ?

android - ERR_UNKNOWN_URL_SCHEME react native webview