简体   繁体   中英

How to check socket is alive (connected) in socket.io with multiple nodes and socket.io-redis

I am using socket.io with multiple nodes, socket.io-redis and nginx. I follow this guide: http://socket.io/docs/using-multiple-nodes/

I am trying to do: At a function (server site), I want to query by socketid that this socket is connected or disconnect

I tried io.of('namespace').connected[socketid] , it only work for current process ( it mean that it can check for current process only).

Anyone can help me? Thanks for advance.

How can I check socket is alive (connected) with socketid I tried namespace.connected[socketid], it only work for current process.

As you said, separate process means that the sockets are only registered on the process that they first connected to. You need to use socket.io-redis to connect all your nodes together, and what you can do is broadcast an event each time a client connects/disconnects, so that each node has an updated real-time list of all the clients.

Check out here

as mentioned above you should use socket.io-redis to get it work on multiple nodes.

var io = require('socket.io')(3000);
var redis = require('socket.io-redis');
io.adapter(redis({ host: 'localhost', port: 6379 }));

I had the same problem and no solution at my convenience. So I made a log of the client to see the different methods and variable that I can use. there is the client.conn.readystate property for the state of the connection "open/closed" and the client.onclose() function to capture the closing of the connection.

const server = require('http').createServer(app);
const io = require('socket.io')(server);
let clients = [];
io.on('connection', (client)=>{
    clients.push(client);
    console.log(client.conn.readyState);
    client.onclose = ()=>{
        // do something
        console.log(client.conn.readyState);
        clients.splice(clients.indexOf(client),1);
    }
});

When deploying Socket.IO application on a multi-nodes cluster, that means multiple SocketIO servers, there are two things to take care of:

Using the Redis adapter and Enabling the sticky session feature: when a request comes from a SocketIO client (browser) to your app, it gets associated with a particular session-id, these requests must be kept connecting with the same process (Pod in Kubernetes) that originated their ids.

you can learn more about this from this Medium story (source code available) https://saphidev.medium.com/socketio-redis...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM