I am developing a node.js application using socket.io to municate 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.
I am developing a node.js application using socket.io to municate 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.
Share Improve this question asked Apr 27, 2015 at 19:14 user1692342user1692342 5,24713 gold badges79 silver badges138 bronze badges1 Answer
Reset to default 5I 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.