socket.io 重新连接是否重新运行连接? [英] Does socket.io reconnects re-run connect?

查看:46
本文介绍了socket.io 重新连接是否重新运行连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经构建了一个简单的 Web 应用程序,它使用 socket.io 通过 node.js 服务器进行一些通信.

I've built a simple web application that does some communication through a node.js server using socket.io.

当用户连接时,节点会返回信息,告诉客户端订阅某些事件.效果很好.

When a user connects, node communicates back info which tells the client to subscribe to certain events. That works fine.

但是,如果您让浏览器设置为空闲,客户端最终会订阅事件两次.订阅过程是这样的:

But if you let the browser set idle, the client ends up subscribed to the events twice. The subscription process works like this:

当用户连接 node.js 时,会收到一条 'adduser' 消息

When a user connects node.js gets a 'adduser' message

该函数中发生的两个关键是:

The two key things that hapen in that function are this:

socket.on('adduser', function(data)
   <snip>
   socket.emit('nodeinfo', {node_id: NODE_ID});
   socket.emit('update', {msg: 'you are connected'});

socket.emit('nodeinfo') 通知客户端订阅事件.

The socket.emit('nodeinfo') signals the client to subscribe to the events.

所以客户有

socket.on('nodeinfo', function(data) { ... }

问题是它永远不会说你已连接"两次,adduser"中的任何 console.log() 函数都不会在节点端再次调用.唯一似乎发生的事情是 node.js 再次发出 nodeinfo(或者客户端认为)导致客户端重新订阅.

The thing is it never say 'you are connected' twice, none of the console.log() functions in 'adduser' get called again on the node side. The only thing that appears to happen is node.js emits nodeinfo again (or so the client thinks) causing the client to re-subscribe.

谁能向我解释一下 socket.io 中的重新连接是如何工作的以及这是如何发生的?

Can anyone explain to me how re-connects in socket.io work and how this may happen?

推荐答案

默认情况下,客户端会在断开连接后尝试重新连接.如果您愿意,可以更改此设置:socket.io 客户端

By default the client tries to reconnect after a disconnect. This can be changed if you like: socket.io client

如果重新连接,服务器将看到一个新连接,由您执行逻辑来识别与前一个连接的新连接.所以在实践中 - 在客户端向服务器发送一些信息之后,而不是在连接"时实现您的 adduser 逻辑.

If reconnected, the server will see a new connection and it is up to you to implement logic to identify the new connection with the previous one. So in practice - instead of implementing your adduser logic upon "connection" do it (or not) after the client sends some info to the server.

这篇关于socket.io 重新连接是否重新运行连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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