i have a problem with using Socket.io.
code is simple:
var socket = null;
var socketInit = false; //if it is true, use reconnect
...
function connect() {
if(!socketInit) {
socket = io();
socketInit = true;
//attach event handlers
socket.on('connect', function() {
console.log('connect fired!');
});
socket.on('disconnect', function() {
console.log('disconnect fired!');
});
socket.on('reconnect', function() {
console.log('reconnect fired!');
});
}
else {
socket.io.connect();
}
}
...
function disconnect() {
socket.disconnect();
}
as you can see, there are two functions that connect or disconnect socket. and in connect function, it attachs 'connect', 'disconnect', 'reconnect' handlers to the socket.
first i called connect function, it works well. server side is also working well. and i called disconnect function, works well too so as the server.
but i called connect function again, that means "socketInit" variable is true, so connect function tries:
socket.io.connect();
i checked the server and client console both, and looks like it has connected, but the problem is the events are not fired!
server side 'connection' event was fired on reconnection but client side 'connect' or 'reconnect' event wasn't fired. i tried to figure out what is going on, but still i don't get it. i checked web console and server console many times, and the connection itself is working fine, but the problem is events are not working!
if someone know the way, it will be very appreciated to help me. thanks ;)
p.s. i tried to add 'reconnected', 'reconnection', 'reconnect_error' event handlers, but neither not works.
Socket disconnects automatically, reconnects, and disconnects again and form a loop. #918.
This is Expert Verified Answer Option a)connect event is fired when a new connection is fired.
You can check the socket. connected property: var socket = io. connect(); console.
If you're using Socket.io 1.0, try using the io manager on the socket to handle manual disconnection and reconnection.
var socket = null;
var socketInit = false;
function connect() {
if(!socketInit) {
socket = io();
socketInit = true;
//attach event handlers
socket.on('connect', function() {
console.log('connect fired!');
});
socket.on('disconnect', function() {
console.log('disconnect fired!');
});
socket.on('reconnect', function() {
console.log('reconnect fired!');
});
}
else {
socket.io.reconnect();
}
}
function disconnect() {
socket.io.disconnect();
}
The reconnecting_attempt, reconnecting, reconnected and connected events on the socket should all be emitted afterwards.
I am using socket.io 2.1.1, and here is all the event sequence that when socket.io handle reconnect after disconnected:
Just do socketClient.on(eventName, callBackFunc);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With