2 回答
TA贡献1810条经验 获得超4个赞
我不确定下面的代码是否有效,但我认为通过使用 socket.io-redis 提供的 customHook,我们可以获得基于 redis 的多节点的 socket.handshake.session。
我希望下面的代码有所帮助。
// get all client in a room
socketServer.in(room_id).clients((err, clients) => {
for (let i = 0, e = clients.length; i < e; i++) {
const client = clients[i];
console.log(client); // print the socket id
// HOW RETRIVE THE SOCKET OBJECT???
}
});
// set root namespace
const rootNamespace = socketServer.of('/');
// define customHook
rootNamespace.adapter.customHook = (request, cb) => {
// every socket.io server execute below, when customRequest requested
const type = request.type;
if(type === 'getHandShakeSession'){
// get all socket objects on local socket.io server
const sockets = rootNamespace.connected;
const socketIDs = Object.keys(sockets);
// get all socket.handshak.session array on local socket.io server
const sessions = socketIDs.map(socketID => sockets[socketID].handshake.session);
cb(sessions)
}
cb()
}
// request customRequest
rootNamespace.adapter.customRequest({type:'getHandShakeSession'},(err,replies) => {
//replies are array which element was pushed by cb(element) on individual socket.io server
//remove empty reply
const filtered = replies.filter(reply => reply !== undefined)
// filtered seems like [[session1,session2,...],[sesssion3,session4,...],..]
console.log(filtered)
} )
添加回答
举报