WebSocket在重新加载应用程序时未关闭(React Native) [英] WebSocket not closed on reload app(React Native)

查看:80
本文介绍了WebSocket在重新加载应用程序时未关闭(React Native)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将WebSocket与React Native一起使用,并且有一些问题.刷新应用程序时,我发现以前的WebSocket连接(在刷新之前使用)仍然有效,并且未正确关闭.每次我重新加载该应用程序时,它都会建立新的连接.然后我关闭该应用程序,它会同时释放所有连接.

I'm using WebSocket with React Native and have some issues on it. When I refresh the app, I found that previous WebSocket connection(used before refresh) was still alive, and not closed properly. Every time I was reloaded the App, it makes new connection. Then I shutdown the app, it releases all connections together.

当我用浏览器测试几乎相同的代码时,刷新页面时,套接字会自动关闭,并在页面加载时创建新的Websocket.

When I'm testing almost same code with browser, when I refresh the page, socket is closed automatically and create new Websocket on page loads.

如果生产环境中仍然存在此问题,则可能非常关键.

If this problem is still existing on production environment, it could be very critical.

这是服务器端代码(我使用express-ws):

This is server side code(I used 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,并在关闭时将其删除.您可以看到我记录了在建立连接时识别出的每个Websocket时使用的Socket ID,它看起来像这样(使用了node-uuid):

Server just saves received WebSocket on connected, and remove it when closed. You can see that I logged Socket id that I made when got connection for identify each websocket handy, it looks like this(used node-uuid):

Socket d0b62d3a-2ed9-4258-9d2d-e83a3eb99e6c disconnected.

好的,当我使用Web浏览器测试此服务器时,它运行良好.每次刷新均成功关闭套接字并创建了一个新套接字.

Ok, when I tested this server with Web browsers, it worked well. Every refresh successfully were closed socket and created new one.

但是使用React Native,套接字在刷新应用程序时永远不会关闭.几次刷新后,最终退出应用程序,突然这些消息立即出现在控制台上:

But with React Native, socket never closed on refresh the app. After several refreshes, and finally exit the app, suddenly these messages were appear on the console at once:

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.

下面的代码是WebSocket处理我的React Native应用程序的一部分.

Below code is WebSocket handling part of my React Native app.

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上找到相关的文章,因此给我一些建议将是非常感谢.谢谢!

If I should close socket before app ends manually, and anyone know about this, please gimme some advice. I'm not much know about React Native, and not found related posts on google, so it will be very appreciate it gimme some advice. Thanks!

P.S.哦,我用Android进行测试.

P.S. Oh, and I used Android for testing.

推荐答案

您的代码看起来不错.刷新是指在调试模式下运行时刷新javascript吗?javascript不会存储在设备中.

Your code looks good. By refresh do you mean refreshing the javascript while running in debug mode? That should never happen in production, the javascript is stored on the device.

如果您需要在后台运行应用程序时明确关闭连接,请签出:

If you need to explicitly close the connection when the app is in the background, check out:

http://facebook.github.io/react-native/docs/appstate.html

然后,当应用程序在后台时,您可以调用 ws.close():)

Then you can call ws.close() when the app is in the background :)

这篇关于WebSocket在重新加载应用程序时未关闭(React Native)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆