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

谁说我不能喝 提交于 2019-12-06 19:01:21

问题


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.


回答1:


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.




回答2:


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 }));



回答3:


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);
    }
});


来源:https://stackoverflow.com/questions/29390562/how-to-check-socket-is-alive-connected-in-socket-io-with-multiple-nodes-and-so

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