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

查看:43
本文介绍了重新连接后,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 来监听第一次连接,后者只在第一次运行 eventhandler.试试

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天全站免登陆