![](/img/trans.png)
[英]Nodejs - Express - Socket.io How to send a message to a specific socket.id from an outside function?
[英]How to send multiple client using socket.id that are connected to socket (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 循環。
是的,它現在解決了!! 下面我們來回答。
io.to(socketid1).to(socketid2).emit("add-message", data);
或者您可以通過將客戶加入一個組來做到這一點。 並向該組發出消息。
加入
socket.join(data.username);
發射
socket.join(data.username);
這使我免於編寫大量代碼
隨意使用我的 Socket.IO Cheatsheet!
// 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');
2020 年更新
這是 Socket.IO 的官方備忘單。
您可以讓所有用戶訂閱一個房間,然后您可以發出消息。
socket.join('some room');
啊! 我沒有正確閱讀文檔! 謝謝大家!:)
我正在尋找這個... io.sockets.emit('Test1', response); 我正在使用這個... socket.emit("Test1", response);
:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.