socket.io在重新连接后再创建一个连接 [英] socket.io creates one more connection after reconnecting

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

问题描述

我正在此处与socket.io一起尝试和node.js.每次我重新启动node.js服务器时,socket.io都会自动重新连接,并以某种方式创建与服务器的另一个连接,即客户端现在两次收到相同的聊天消息.我该如何解决?

I am trying a simple chat application here with socket.io and node.js. Every time I restart the node.js server, socket.io automatically reconnects and somehow creates one more connection to the server, i.e. the client now receives the same chat message twice. How do I fix this?

推荐答案

默认情况下,断开socket.io会重新连接丢失的连接,并重新运行connect事件.因此,每次重新连接时,您都会添加一个事件侦听器以接收消息.因此,您收到的消息数量等于服务器重新启动/连接丢失的数量.

By default on disconnect socket.io reconnects the lost connection, which re runs the connect event. So everytime it reconnects you add one more event listener for recieving messages. So you get multiple number of messages equal to server restarts/connection loss.

Incoming Chat: 
Connected
dsdadsada
Disconnected                         //recieved by 1st listener
Connected                            //added 2nd listener
adasd
Disconnected                         //recieved by 1st listener
Disconnected                         //recieved by 2nd listener
Connected                            //added 3rd listener

您应该使用once而不是on来监听第一次连接,后者仅在第一次运行事件处理程序.试试

You should listen to the first connect using once instead of on, which runs eventhandler the first time only. Try

iosocket.once('connect', function () {

代替

iosocket.on('connect', function () {

这篇关于socket.io在重新连接后再创建一个连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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