如何在 socket.io 中获取所有连接的客户端 [英] how to Get all connected clients in socket.io

查看:162
本文介绍了如何在 socket.io 中获取所有连接的客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 socket.io v2.3,我正在尝试从不同的文件中获取所有连接的套接字.这是我的设置:

const io = require('socket.io');让 IO;让我的名字IO;模块.出口 = {创建:(服务器)=>{IO = io(server, { cors: { origin: '*' } });const redisConnection = redisAdapter({ host: redisHost, port: redisPort });IO.适配器(redisConnection);IO.on('connection', (socket) => {console.log('一个用户已连接');});IO.on('disconnect', (socket) => {console.log('断开连接');});myNameIO = IO.of('/我的名字');myNameIO.on('connection', function (socket) {console.log('有人连接');});},getIO: () =>IO,getMyNameIO: () =>我的名字IO,};

在差异文件中,我导入 getMyNameIO 并且我正在尝试获取所有已连接的客户端,但我遇到了问题.尝试过

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

但是客户端不是一个函数.然后我尝试导入 socket.io 和 use.of,但没有返回任何内容.哪里做错了,我该如何解决?

解决方案

试试这个.我怀疑是范围问题或操作顺序问题.无论哪种方式,这都应该解决它或给你一个更有用的错误.我试图维护你的命名方案,这让我有点头疼.=)

const io = require('socket.io');const socketServer = {_初始化:假,_myNameIO:空,_IO:空,_myNameIOClients:新地图(),获取 myNameIO() {if (!socketServer._initialized) throw new Error('socketServer.create not called!')返回 socketServer._myNameIO},获取 IO() {if (!socketServer._initialized) throw new Error('socketServer.create not called!')返回 socketServer._IO},创建:(服务器)=>{IO = io(server, { cors: { origin: '*' } });const redisConnection = redisAdapter({ host: redisHost, port: redisPort });IO.适配器(redisConnection);IO.on('connection', (socket) => {console.log('一个用户已连接');});IO.on('disconnect', (socket) => {console.log('断开连接');});myNameIO = IO.of('/我的名字');myNameIO.on('connection', function (socket) {console.log('有人连接');socketServer._myNameIOClients.set(socket.id, socket)});},//getIO: () =>IO,//getMyNameIO: () =>我的名字IO,getIO: () =>socketServer._IO,getMyNameIO: () =>socketServer._myNameIO,获取 myNameIOClients() {返回 socketServer._myNameIOClients},getClients: () =>new Promise((resolve,reject)=>socketServer._myNameIO.clients((error,clients)=>error?reject(error):resolve(clients))}),};module.exports = socketServer

<块引用>

当我做 console.log(socketServer.myNameIO.sockets);我得到一个带有所有套接字的对象.我怎样才能得到一个数组?

查看 API https://socket.io/docs/v2/server-api/#Namespace 我没有看到对 Namespace.sockets 的引用.这并不意味着它不存在.我添加了一个 getClients 函数,该函数将返回一组客户端 ID.

const socketServer = require('./socketServer ')socketServer.getClients().then(客户端=>{//客户端客户端 ID 数组}).catch(e=>console.error('Error is socketServer.getClients()', e))

我认为您真正想要的是管理连接.一种方法是在连接进来时映射它们.

const socketServer = require('./socketServer ')//这是一张地图让 myNameIOClients = socketServer.myNameIOClients//如果需要,我们可以很容易地把它变成一个数组让 myNameIOClientsArray = Array.from(socketServer.myNameIOClients)

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)

这篇关于如何在 socket.io 中获取所有连接的客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆