我想将数据发送到一个特定的套接字ID。
我们以前可以在旧版本中执行此操作:
io.sockets.socket(socketid).emit('message', 'for your eyes only');
我将如何在Socket.IO 1.0中执行类似的操作?
我想将数据发送到一个特定的套接字ID。
我们以前可以在旧版本中执行此操作:
io.sockets.socket(socketid).emit('message', 'for your eyes only');
我将如何在Socket.IO 1.0中执行类似的操作?
Answers:
在socket.io 1.0中,它们为此提供了更好的方法。每个套接字通过自身ID自动加入默认房间。检查文件:http : //socket.io/docs/rooms-and-namespaces/#default-room
因此,您可以使用以下代码通过id向套接字发出消息:
io.to(socketid).emit('message', 'for your eyes only');
在socket.io 1.0中,您可以使用以下代码进行操作:
if (io.sockets.connected[socketid]) {
io.sockets.connected[socketid].emit('message', 'for your eyes only');
}
更新:
@MustafaDokumacı的答案包含一个更好的解决方案。
@MustafaDokumacı和@Curious已经提供了足够的信息,我正在添加如何获取套接字ID。
要获取套接字ID,请使用socket.id:
var chat = io.of("/socket").on('connection',onSocketConnected);
function onSocketConnected(socket){
console.log("connected :"+socket.id);
}
如果您使用了命名空间,则会发现以下工作原理:
//Defining the namespace <br>
var nsp = io.of('/my-namespace');
//targeting the message to socket id <br>
nsp.to(socket id of the intended recipient).emit('private message', 'hello');
有关名称空间的更多信息:http : //socket.io/docs/rooms-and-namespaces/
我相信@Curious和@MustafaDokumacı都提供了很好的解决方案。但是,不同之处在于,使用@MustafaDokumacı的解决方案时,消息将广播到房间,而不仅是特定的客户端。
当请求确认时,差异非常明显。
io.sockets.connected[socketid].emit('message', 'for your eyes only', function(data) {...});
如预期般运作
io.to(socketid).emit('message', 'for your eyes only', function(data) {...});
失败于
Error: Callbacks are not supported when broadcasting