Node.js 曾经是我真正感兴趣的东西,我在我的一个项目中使用它来制作多人游戏。
io.sockets.in().emit() 和 socket.broadcast.to().emit() 是我们在 Socket.io 的房间 (https://github.com/LearnBoost/socket.io/wiki/Rooms) 中使用的主要两种发射方法,房间允许对连接的客户端进行简单的分区。这允许将事件发送到已连接客户端列表的子集,并提供一种简单的管理方法。
它们允许我们管理连接的客户端列表(我们称之为房间)的子集,并具有类似的功能,如 socket.io 的主函数 io.sockets.emit() 和 socket.broadcast.emit()。
无论如何我会尝试给出带有cmets的示例代码来解释。看看有没有帮助;
Socket.io 房间
i) io.sockets.in().emit();
/* Send message to the room1. It broadcasts the data to all
the socket clients which are connected to the room1 */
io.sockets.in('room1').emit('function', {foo:bar});
ii) socket.broadcast.to().emit();
io.sockets.on('connection', function (socket) {
socket.on('function', function(data){
/* Broadcast to room1 except the sender. In other word,
It broadcast all the socket clients which are connected
to the room1 except the sender */
socket.broadcast.to('room1').emit('function', {foo:bar});
}
}
Socket.io
i) io.sockets.emit();
/* Send message to all. It broadcasts the data to all
the socket clients which are connected to the server; */
io.sockets.emit('function', {foo:bar});
ii) socket.broadcast.emit();
io.sockets.on('connection', function (socket) {
socket.on('function', function(data){
// Broadcast to all the socket clients except the sender
socket.broadcast.emit('function', {foo:bar});
}
}
干杯