简体   繁体   English

为什么手动重新连接 Socket.IO 时不触发重新连接功能

[英]Why does the reconnect function not trigger on manual reconnect Socket.IO

When the node server disconnects the client using socket.disconnect(true);当节点服务器使用socket.disconnect(true);断开客户端连接时socket.disconnect(true); I manually open the connection again on the client side using socket.open() .我使用socket.open()在客户端再次手动打开连接。

The problem is that when the socket.open() is triggered, the socket.on('reconnect', (attemptNumber) => { function isn't. socket.on('connect', () => { works fine, but I'd like the code inside to only execute on a reconnect after the server has closed on the connection. Why doesn't the reconnect function work on a manual reconnect and is there something I can do to fix or work around this problem?问题是当socket.open()被触发时, socket.on('reconnect', (attemptNumber) => {函数不是socket.on('connect', () => {工作正常,但我希望里面的代码只在服务器关闭连接后重新连接时执行。为什么重新连接功能在手动重新连接时不起作用,我可以做些什么来修复或解决这个问题?

You could handle it just like in this very simple implementation:您可以像在这个非常简单的实现中一样处理它:

class SocketService {
    .
    .
    .
    static registerSocket(opts) {
        socket.on('open', () => { 
            console.log('socket connected')
            socket.onclose = (e) => {
                console.log('Socket is closed. Reconnect will be attempted in 1.5 second.', e.reason); 
                setTimeout(() =>
                    /* 
                    * Try connect again after 1.5s, 
                    * could be improved with a while 
                    * and a number max of retries
                    */
                    SocketService
                        .registerSocket(opts)
                ,1500); 
            };
        });
        socket.onerror = () => {
            // Handle first connection error here
        };
    }
}

Implementing this way, you have some insurances.以这种方式实施,你有一些保险。

The first one is that you ensure that you're handling the reconnection logic and the second is the you're handling the connection error as well一个是确保您正在处理重新连接逻辑,第二个是您也在处理连接错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM