提问者:小点点

React Native STOMP over websocket


我正在尝试通过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]);

  ...
}

当安装上述组件时,我得到:

哎呀!失去了与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-timp,结果是相同的。

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

谢谢你的帮助谢谢


共2个答案

匿名用户

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

匿名用户

import SockJS from "sockjs-client";
import Stomp from "webstomp-client";
var connected =false;
var socket ='';
var stompClient = '';
const  send = ()=> {
      let send_message = 'hello !';
      if (stompClient && stompClient.connected) {
        const msg = { name: send_message };
        stompClient.send("/app/hello", JSON.stringify(msg), {});
      }
    }
    const connect =()=> {
      socket = new SockJS("http://uat.wealthbrain.com:7777/gs-guide-websocket");
      stompClient = Stomp.over(socket);
      stompClient.connect(
        {},
        frame => {
          connected = true;
          stompClient.subscribe("/topic/greetings", tick => {
          });
        },
        error => {
          console.log(error);
          connected = false;
        }
      );
    }
    const disconnect =()=> {
      if (stompClient) {
        stompClient.disconnect();
      }
      connected = false;
    }
    const tickleConnection =()=> {
      connected ? disconnect() : connect();
    }