简体   繁体   中英

how to Get all connected clients in socket.io

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?

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)

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