android - 通过 websocket react Native STOMP

标签 android react-native websocket stomp sockjs

我正在尝试通过 websocket 和 STOMP 协议(protocol)(​​对于服务器端我使用 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]);

  ...
}

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

Whoops! Lost connection to http://localhost:8080/chat



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

Whoops! Lost connection to http://localhost:8080/chat



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

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

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

我很感激任何帮助。谢谢

最佳答案

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

关于android - 通过 websocket react Native STOMP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61975364/

相关文章:

android浏览器输入比例问题

javascript - 在 React Native 中从图像中删除背景

javascript - 我可以通过 Javascript 建立套接字连接吗

android - 适用于 Android 和 iOS 的 MQTT over websocket

react-native - 为什么 AsyncStorage getItem 返回 null?

javascript - 如何获取两个服务器的cookie 1.运行应用程序(HTTP),2.运行websocket(WS)服务器?

java - 无法分配给manifest.xml中的android.app.activity

android - android/gradle 3.2.1排除文件不起作用

c# - 如何找到 VLC 属性库 (C# Unity)

javascript - 如何在 React Native 页面中协调状态更改?