首页 > 解决方案 > 通过 websocket 反应 Native STOMP

问题描述

我正在尝试通过 websocket 和 STOMP 协议(​​对于服务器端我使用 Spring Boot)构建一个 React Native 消息传递应用程序,但我得到了一个非常奇怪的行为。我的代码如下:

...
import SockJS from 'sockjs-client'; // Note this line
import Stomp from 'stompjs';

function ChatScreen() {
   // Variables declaration

   useEffect(() => {
    const socket = new SockJS('http://localhost:8080/chat');
    const stompClient = Stomp.over(socket);
    const headers = {Authorization: `Bearer ${jwt}`};

    stompClient.connect(headers, () => {
      stompClient.subscribe(
        `/user/${user.username}/queue/messages`, console.log, headers,
      );
    });

    return () => stompClient && stompClient.disconnect();
  }, [jwt, user.username]);

  ...
}

安装上述组件后,我得到:

哎呀!失去与http://localhost:8080/chat的连接

然后,如果我将 SockJS 导入行从更改import SockJS from 'sockjs-client';import SockJS from 'sockjs-client/dist/sockjs';不使用双“r”重新加载,但让热重新加载完成它的工作,我成功获得到 websocket 的连接,一切正常。现在,如果我用双“r”重新加载并再次导航到 ChatScreen 组件,我仍然会收到消息:

哎呀!失去与http://localhost:8080/chat的连接

切换回import SockJS from 'sockjs-client';fromimport SockJS from 'sockjs-client/dist/sockjs';我成功地获得了一个新的工作连接,但双“r”再次将其断开。

我在模拟器(Android 9)和物理设备(Android 10)上测试了代码。我还测试了 react-stomp,结果是一样的。

为了更好地理解我的意思,这是一个报告行为的视频: https ://drive.google.com/open?id=1IVpiJjHsBGkhB38IWoPujI5eXPuBDbf1

我很感激任何帮助。谢谢

标签: androidreact-nativewebsocketstompsockjs

解决方案


我找到了解决方案,因为我在 Android 模拟器上我不能http://localhost:8080/chat用来连接到 websocket,所以我必须使用它http://10.0.2.2:8080/chat。更多细节在这里: https ://stackoverflow.com/a/5495789/9121838


推荐阅读