Node.js一直是我真正感兴趣的东西,我在一个项目中使用它来制作多人游戏。
io.sockets.in().emit()
这socket.broadcast.to().emit()
是我们在Socket.io的房间(https://github.com/LearnBoost/socket.io/wiki/Rooms)中使用的主要两种发出方法。房间允许对连接的客户端进行简单分区。这允许将事件与连接的客户端列表的子集一起发出,并提供一种简单的方法来管理它们。
它们使我们能够管理连接的客户端列表的子集(我们称为房间),并具有类似的功能,例如main socket.io函数io.sockets.emit()
和socket.broadcast.emit()
。
无论如何,我将尝试给出示例代码以及注释以进行解释。看看是否有帮助;
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});
}
}
套接字
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});
}
}
干杯