user1692342
user1692342

Reputation: 5237

socket.io not reconnecting after a disconnect

I am developing a node.js application using socket.io to communicate between server and client. If the server faces any error, I send an error message to the client and I close the connection from both server and client. However when the client tries to reconnect, it is no longer able to connect to the server. My code

server.js

io.sockets.on('connection', function(socket) {

   /*Some code*/
   stream.on('error',function(errormsg){
        socket.emit('error',{txt: "Error!"});
        socket.disconnect();
   });
});

client.js

var server_name = "http://127.0.0.1:5000/";
var socket = io.connect(server_name);

socket.on('error',function(data){
   console.log(data.txt);
   socket.disconnect();
});

function submitclick()
{
  var text="hello";
  if(socket.connected ==false)
    socket= io.connect({'forceNew': true});
  console.log(socket.connected);
}

Status of socket.connected is false. I do not receive it on the server side either.

Upvotes: 5

Views: 3897

Answers (1)

Andrew Lavers
Andrew Lavers

Reputation: 8141

I don't think your call to io.conncet is synchronous, you're checking socket.connected too early. If you want to verify that your reconnect succeeds, try it like this:

function submitclick()
{
  var text="hello";
  if(socket.connected ==false) {
    socket= io.connect({'forceNew': true});
    socket.on('connect', function() {
      console.log('Connected!');
    });
  }
}

Edit: As @jfriend00 points out there's probably no need for you to do the socket.disconnect() in the first place as socket.io should automatically be handling reconnection.

Upvotes: 5

Related Questions