how to Get all connected clients in socket.io

大憨熊 提交于 2020-12-12 05:41:46

问题


I have socket.io v2.3 and I'm trying to get all connected sockets from a different file. Here's my setup:

const io = require('socket.io');
let IO;
let myNameIO;

module.exports = {
    create: (server) => {
        IO = io(server, { cors: { origin: '*' } });
        const redisConnection = redisAdapter({ host: redisHost, port: redisPort });
        IO.adapter(redisConnection);

        IO.on('connection', (socket) => {
            console.log('a user connected');
        });
        IO.on('disconnect', (socket) => {
            console.log('disconnected');
        });

        myNameIO = IO.of('/my-name');
        myNameIO.on('connection', function (socket) {
            console.log('someone connected');
        });
    },
    getIO: () => IO,
    getMyNameIO: () => myNameIO,
};

IN a diff file I import getMyNameIO and I'm trying to get all connected clients but I'm having trouble with that. Tried doing

getMyNameIO().clients((error, clients) => {
    console.log(clients, '-=--=-=');
});

But clients isn't a function. I then tried importing the socket.io and use.of, but that doesn't return anything. What am doing wrong and how can I fix it?


回答1:


Give this a try. I suspect either a scope issue or order of operations issue. Either way this should resolve it or give you a more useful error. I've tried to maintain your naming scheme which gave me a small headache. =)

const io = require('socket.io');
const socketServer = {
    _initialized: false,
    _myNameIO: null,
    _IO: null,
    _myNameIOClients: new Map(),
    get myNameIO() {
        if (!socketServer._initialized) throw new Error('socketServer.create not called!')
        return socketServer._myNameIO
    },
    get IO() {
        if (!socketServer._initialized) throw new Error('socketServer.create not called!')
        return socketServer._IO
    },
    create: (server) => {
        IO = io(server, { cors: { origin: '*' } });
        const redisConnection = redisAdapter({ host: redisHost, port: redisPort });
        IO.adapter(redisConnection);

        IO.on('connection', (socket) => {
            console.log('a user connected');
        });
        IO.on('disconnect', (socket) => {
            console.log('disconnected');
        });

        myNameIO = IO.of('/my-name');
        myNameIO.on('connection', function (socket) {
            console.log('someone connected');
            socketServer._myNameIOClients.set(socket.id, socket)
        });

    },
    //getIO: () => IO,
    //getMyNameIO: () => myNameIO,
    getIO: () => socketServer._IO,
    getMyNameIO: () => socketServer._myNameIO,
    get myNameIOClients() {
       return socketServer._myNameIOClients
    },
    getClients: () => new Promise((resolve,reject)=>socketServer._myNameIO.clients((error, clients)=> error ? reject(error) : resolve(clients))
}),
};
module.exports = socketServer

when I do console.log(socketServer.myNameIO.sockets); I get an object with all the sockets. how can I get an array?

Looking at the API https://socket.io/docs/v2/server-api/#Namespace I don't see a reference to Namespace.sockets. That doesn't mean it doesn't exist. I added a getClients function that will return an array of client IDs.

const socketServer = require('./socketServer ')
socketServer.getClients()
    .then(clients=>{
       // clients an array of client IDs
    })
    .catch(e=>console.error('Error is socketServer.getClients()', e))

I think what you really want is to manage the connections. One way to do it is by mapping the connections as they come in.

const socketServer = require('./socketServer ')

// This is a Map
let myNameIOClients = socketServer.myNameIOClients
// We can easily turn it into an array if needed
let myNameIOClientsArray = Array.from(socketServer.myNameIOClients)



来源:https://stackoverflow.com/questions/65173742/how-to-get-all-connected-clients-in-socket-io

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