首页 > 解决方案 > 如何使用连接到套接字的socket.id发送多个客户端(Nodejs,Socket.io)

问题描述

socket.on('private-message', function(data){
        console.log("Sending: " + data.content + " to " + data.username);
        console.log(clients[data.username].socket.join(', '));
        if (clients[data.username]){    
            io.sockets.connected[clients[data.username].socket].emit("add-message", data);
        } else {
            console.log("User does not exist: " + data.username);
        }
    });

这段代码工作正常,但我想要的是,我想发送多个连接的客户端,使用它们的套接字 id 连接到套接字。

io.sockets.connected[reciver.socketid].emit("add-message", data);

有什么办法或者是否可以编写接收者socket.id的组。我不想使用 for 循环。

标签: node.jssocket.io

解决方案


随意使用我的 Socket.IO 备忘单!

// Add socket to room
socket.join('some room');

// Remove socket from room
socket.leave('some room');

// Send to current client
socket.emit('message', 'this is a test');

// Send to all clients include sender
io.sockets.emit('message', 'this is a test');

// Send to all clients except sender
socket.broadcast.emit('message', 'this is a test');

// Send to all clients in 'game' room(channel) except sender
socket.broadcast.to('game').emit('message', 'this is a test');

// Send to all clients in 'game' room(channel) include sender
io.sockets.in('game').emit('message', 'this is a test');

// Send to individual socket id
io.sockets.socket(socketId).emit('message', 'this is a test');

2021 年更新

这是Socket.IO的官方备忘单。


推荐阅读