Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

socket.io disconnect then reconnect

Tags:

socket.io

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');
    });
});
like image 851
Ludo Avatar asked Dec 07 '22 04:12

Ludo


2 Answers

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

like image 58
kmftzg Avatar answered Feb 19 '23 20:02

kmftzg


The answer is to use Socket.socket.reconnect();

(where Socket is the "original" socket returned by the connection event).

like image 41
Ludo Avatar answered Feb 19 '23 18:02

Ludo