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

查看:734
本文介绍了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) { ... }

事情是它从来不说'你连接'两次, console.log()函数在'adduser'中在节点端再次调用。看来发生的唯一事情是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天全站免登陆