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

孤街浪徒 提交于 2019-12-05 00:16:28

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.

vromanch

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);
    }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!