简体   繁体   中英

Reconnection in socket.io problem in `socket.on('message',function(){})`

I have a socket.io connection to connect to server and client,
It work fine.
Now when I try to reconnect it on disconnect from server it get connected but then socket.on('message' doesnt get fired any more.
I checked it from server side it is pushing that message.

Please suggest me some thing I am out of ideas now .
I am sure that problem is on client side socket.on message

Client side code

var socket = new io.Socket('some host name',{port:80,rememberTransport:true});
socket.on('connect', function(){
    clearInterval(socketInterval);
});
socket.on('message', function(obj)
{
    alert("meg from server");
});
socket.on('disconnect', function()
{
    socketInterval=setInterval("socket.connect()",5000);
});
socket.connect();

I don't know node.js, but it looks like syntax error, haven't you forgot the right paratheses?

socket.on('connect', function(){
    clearInterval(socketInterval);
});
socket.on('message', function(obj)
{
    alert("meg from server");
});
socket.on('disconnect', function()
{
    socketInterval=setInterval("socket.connect()",5000);
});

it would appear that the "problem" most likely is on the server side. The server has two ways to send messages to the client (emit and broadcast). If you are doing a one to one message, most people use emit. I am assuming that you built a chat server which stores the sessionIds of the client. It works fine with the initial connection because the server has the correct sessionId, but let's say connection is lost and you reestablish connection, now the server tries to send a message to the client. If your server stored the initial sessionId, say in an array, and attempts to use the original sessionId to emit a message, it will fail because reconnection causes a new sessionId to be created.

The solution in this case is to remove the previous sessionId from the array and add the new sessionId upon reconnection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM