5

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.

user1692342
  • 5,007
  • 11
  • 69
  • 128

1 Answers1

5

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.

Andrew Lavers
  • 8,023
  • 1
  • 33
  • 50
  • 2
    One of the main features of socket.io is that it does auto-reconnect for you. I don't see why you would need to manually reconnect it if it is configured properly. Said another way, properly configured socket.io code should not have to include the code in your answer. Make a connection once and let socket.io handle the reconnection for you. – jfriend00 Apr 27 '15 at 20:14