如何使用连接到套接字的socket.id发送多个客户端(Node.js,Socket.io)

Bis*_*jit 0 node.js 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);
        }
    });
Run Code Online (Sandbox Code Playgroud)

这段代码可以正常工作,但是我想要的是,我想使用其套接字ID发送多个连接到套接字的已连接客户端。

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

有什么办法可以写接收者socket.id组吗?我不想使用for循环。

Bis*_*jit 7

是的,它现在解决了!!下面我们来回答。

io.to(socketid1).to(socketid2).emit("add-message", data);
Run Code Online (Sandbox Code Playgroud)

或者您可以通过将客户加入一个组来做到这一点。并向该组发出消息。

加入

socket.join(data.username);
Run Code Online (Sandbox Code Playgroud)

发射

socket.join(data.username);

这使我免于编写大量代码


Tam*_*oke 5

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

// Socket.IO Cheatsheet

// 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');
Run Code Online (Sandbox Code Playgroud)