I am trying to disconnect a client, then reconnect it.
I am able to disconnect the client from the server side using socket.disconnect();
But i can't connect it again, is there a way to do it ?
The thing is i have a specific treatment in the client connect callback
, and if i try to connect the client after the disconnect event, it never fires the callback, i don't understand why.
Here is a clear example:
CLIENT
var Socket = io.connect('http://127.0.0.1:3000');
function bind_socket(Socket) {
Socket.on('connect', function() {
console.log('Socket connected !');
});
Socket.on('event', function(data) {
console.log('Receive event: '+data);
});
Socket.on('disconnect', function() {
console.log('Socket disconnected !');
var Socket = io.connect('http://127.0.0.1:3000'); //Doesn't fire the "connect" callback
bind_socket(Socket);
Socket.emit('event', 3);
});
}
bind_socket(Socket);
Socket.emit('event', 1);
SERVER
var io = require('socket.io').listen(3000);
io.on('connection', function(socket) {
console.log('socket '+socket.id+' connect');
socket.on('event', function(data) {
console.log('Receive Event: '+data);
socket.disconnect();
this.emit('event', 2);
});
socket.on('disconnect', function() {
console.log('socket '+this.id+' disconnect');
});
});
If you're using Socket.io 1.0, try using the io
manager on the socket to do disconnect()
and reconnect()
See the example on Socket.io - Manual reconnect after client-side disconnect
The answer is to use Socket.socket.reconnect();
(where Socket
is the "original" socket returned by the connection event).
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