node.js - 如何使用连接到套接字的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 循环。
解决方案
随意使用我的 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的官方备忘单。
推荐阅读
- css - 反应表中过滤器的自定义样式
- python - Python、深度学习、梯度下降法示例
- mongodb - 使用 golang 从 mongodb 集合中获取特定的键值对
- azure - 在 Azure 容器中运行 docker 命令
- mysql - datadrip 和 phpmyadim 上不显示数据库关系线
- ubuntu-16.04 - 如何阻止 icmpv6 邻居广告风暴
- python - 具有两个以上输入的 Keras 自定义指标
- amazon-web-services - Kubernetes 服务无法在 AWS-EKS 上访问
- php - symfony 更新 2.6 到 3.4 后奏鸣曲/树枝错误
- c# - 不要在 localDataBace 中显示插入平铺第二次插入