问题
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:
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'});
The socket.emit('nodeinfo') signals the client to subscribe to the events.
So the client has
socket.on('nodeinfo', function(data) { ... }
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.
Can anyone explain to me how re-connects in socket.io work and how this may happen?
回答1:
By default the client tries to reconnect after a disconnect. This can be changed if you like: socket.io client
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.
来源:https://stackoverflow.com/questions/9668996/does-socket-io-reconnects-re-run-connect