我正在尝试通过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';
切换回import SockJS from 'sockjs-client/dist/sockjs';
我成功获得了一个新的工作连接,但双“ r”再次断开该连接。我在模拟器(Android 9)和物理设备(Android 10)上都测试了代码。我还测试了react-stomp,结果是相同的。
为了更好地理解我的意思,这是一个记录行为的视频:https://drive.google.com/open?id=1IVpiJjHsBGkhB38IWoPujI5eXPuBDbf1
感谢您的帮助。谢谢
我正在尝试通过websocket和STOMP协议构建一个React Native消息传递应用程序(对于服务器端,我正在使用Spring Boot),但是我的行为确实很奇怪。我的代码如下:... ...
我找到了解决方案,因为我使用的是Android模拟器,所以无法使用http://localhost:8080/chat
连接到网络套接字,而必须使用http://10.0.2.2:8080/chat
。此处有更多详细信息:https://stackoverflow.com/a/5495789/9121838