通过 websocket 响应原生 STOMP

Ste*_*lla 5 android stomp websocket sockjs react-native

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

...
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]);

  ...
}
Run Code Online (Sandbox Code Playgroud)

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

哎呀!与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';from import SockJS from 'sockjs-client/dist/sockjs';I 成功获得一个新的工作连接,但双“r”再次将其分解。

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

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

我很感激任何帮助。谢谢

Ste*_*lla 1

我找到了解决方案,因为我使用的是 Android 模拟器,所以我无法使用它http://localhost:8080/chat来连接到 websocket,http://10.0.2.2:8080/chat所以我必须使用它。更多详细信息请参见: /sf/answers/384705261/