Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
573 views
in Technique[技术] by (71.8m points)

node.js - socket.io creates one more connection after reconnecting

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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

instead of

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...