获取套接字对象

Get socket object

我将 socket.io 与 redis 一起使用,我需要获取套接字对象,因为我需要访问在中间件期间添加的数据。

当我这样做时:

const { socketServer } = require('../../socket/socket');
const allSockets = await socketServer.myNamespace.adapter.sockets(new Set());

我只得到套接字 ID,而不是套接字对象。如何获取套接字对象?

使用:
socket.io: 4.0.1.
socket.io-redis: 6.1.0

更新

const socketServer = {
    _initialized: false,
    _IO: null,
    _myNamespace: null,
    get IO() {
        if (!socketServer._initialized) throw new Error('socketServer.create not called!');
        return socketServer._IO;
    },
    get myNamespace() {
        if (!socketServer._initialized) throw new Error('socketServer.create not called!');
        return socketServer._myNamespace;
    },
    create: (server) => {
        const { initMyNamespace } = require('./setupHandler');

        socketServer._IO = io(server, { cors: { origin: '*' } });

        const redisPort = config.get('redisPort');
        const redisHost = config.get('redisHost');

        const redisConnection = redisAdapter({ host: redisHost, port: redisPort });

        socketServer._IO.adapter(redisConnection);

        // inits
        socketServer._myNamespace = socketServer._IO.of('myNamespace');

        // Middlewares
        socketServer._myNamespace.use(auth);

        socketServer._myNamespace.on('connection', function (socket) {
            initMyNamespace(socket);
        });
    
        socketServer._initialized = true;
    },
};

在 api 调用的另一个文件中:

router.post('/', async (req, res) => {
    const { socketServer } = require('../../socket/socket');

    let selectedSockets = [];
    const allSockets = await socketServer.myNamespace.adapter.sockets(new Set());
    
    const userCoordinates = req.body.coordinates;
    for (const currentSocketObj of allSockets) {
        if (isNear(userCoordinates, currentSocketObj.user.coordinates)) {
            const distanceToLocation = distanceCalc(userCoordinates, currentSocketObj.user.coordinates);
            currentSocketObj.distanceToLocation = distanceToLocation;
            selectedSockets.push(currentSocketObj);
        }
    }
    
    for (const currentSocketObj of selectedSockets) {
        currentSocketObj.emit('testing123', {distance: currentSocketObj.distanceToLocation} );
    }
});

在 socket.io v4 中,您可以:

// return all Socket instances
const sockets = await io.fetchSockets();

或者,如果您有一个 socketID,您可以通过以下方式获取该套接字:

// return all Socket instances in the "room1" room of the main namespace
const sockets = await io.in(theSocketID).fetchSockets();

两者都调用 return 可迭代的套接字。


如果(根据您的评论),您正在尝试获取正在连接的特定套接字,那么 socket 应该已经在基于获取您的事件处理程序的范围内首先调用。如果您在上下文中显示该代码,我们可能会向您显示 socket 引用在其中。