我正在使用带有React Native的WebSocket并且有一些问题.当我刷新应用程序时,我发现之前的WebSocket连接(在刷新之前使用)仍然存在,并且没有正确关闭.每次我重新加载应用程序时,它都会建立新的连接.然后我关闭了应用程序,它将所有连接一起释放.
当我使用浏览器测试几乎相同的代码时,当我刷新页面时,套接字会自动关闭并在页面加载时创建新的Websocket.
如果生产环境中仍存在此问题,则可能非常关键.
这是服务器端代码(我使用了express-ws):
const sockets = {}; app.ws('/',(socket,req) => { // Generate unique id to socket and save to socket list const uid = uuid.v4(); socket.uid = uid; console.log(`Socket ${uid} connected.`); sockets[uid] = socket; socket.on('message',(data) => { broadcast(data); }); socket.on('close',() => { console.log(`Socket ${uid} disconnected.`); delete sockets[uid]; broadcast({ type: 'plain',message: `User ${socket.username} leaved the channel.` }); socket = null; // make sure to remove socket }); });
服务器只保存已连接的WebSocket,并在关闭时将其删除.你可以看到我记录了我在连接时创建的Socket id,用于识别每个websocket方便,它看起来像这样(使用node-uuid):
Socket d0b62d3a-2ed9-4258-9d2d-e83a3eb99e6c disconnected.
好吧,当我使用Web浏览器测试此服务器时,它运行良好.每次刷新成功都是关闭套接字并创建新套接字.
但是使用React Native,socket在刷新应用程序时永远不会关闭.经过几次刷新,最后退出应用程序后,这些消息突然出现在控制台上:
Socket d0b62d3a-2ed9-4258-9d2d-e83a3eb99e6c disconnected. Socket 2e1a2bba-ac64-4368-aeca-a02721f28ce5 disconnected. Socket 6673c9a3-9667-425a-8923-efbc40196226 disconnected. Socket 08fee145-e9bf-4af0-a245-dda2fe6a8e56 disconnected. Socket 55ce1926-d7fa-488b-92d9-ff3dea874496 disconnected. Socket 9c4c166d-d6d6-4a11-b400-a3eac51ab91f disconnected. Socket 9f6db512-649c-440e-8b88-9a77d20e1943 disconnected. Socket a9e6c0bd-419c-40af-865a-2573eca26a0f disconnected. Socket 70835c7a-3230-4e20-b133-b6c2942dff22 disconnected. Socket 5c83d81c-c0f1-4b9a-b5fb-7f09430a2f09 disconnected. Socket 4f11aea4-d0ad-4e2b-9613-9e994657ecaf disconnected.
下面的代码是我的React Native应用程序的WebSocket处理部分.
import store from './store'; import * as ChatActions from './actions/Chat'; import * as NetworkActions from './actions/Network'; const socket = null; export function init() { socket = new WebSocket('ws://mywebsite.com:3300'); socket.onopen = () => { store.dispatch({ type: NetworkActions.NETWORK_SOCK_CONNECTED,data: {} }); }; socket.onmessage = (e) => { var data = e.data; try { data = JSON.parse(e.data); } catch(err) {} store.dispatch({ type: ChatActions.CHAT_RECV,data: data.message }); }; socket.onclose = (e) => { store.dispatch({ type: NetworkActions.NETWORK_SOCK_CLOSED,data: {} }); }; } export function send(data) { data = typeof data === 'object' ? JSON.stringify(data) : data; socket.send(data); }
如果我应该在应用程序结束之前关闭套接字,并且任何人都知道这一点,请给我一些建议.我对React Native不是很了解,也没有在google上找到相关的帖子,所以非常感谢它给我一些建议.谢谢!
附:哦,我用Android进行测试.