88

我想将数据发送到一个特定的套接字 ID。

我们曾经能够在旧版本中做到这一点:

io.sockets.socket(socketid).emit('message', 'for your eyes only');

我将如何在 Socket.IO 1.0 中做类似的事情?

4

7 回答 7

210

In socket.io 1.0 they provide a better way for this. Each socket automatically joins a default room by self id. Check documents: http://socket.io/docs/rooms-and-namespaces/#default-room

So you can emit to a socket by id with following code:

io.to(socketid).emit('message', 'for your eyes only');
于 2014-06-14T20:45:56.503 回答
95

在 socket.io 1.0 中,您可以使用以下代码执行此操作:

if (io.sockets.connected[socketid]) {
    io.sockets.connected[socketid].emit('message', 'for your eyes only');
}

更新:

@MustafaDokumacı 的答案包含更好的解决方案。

于 2014-06-04T18:06:58.907 回答
17

@Mustafa Dokumacı 和 @Curious 已经提供了足够的信息,我正在添加如何获取套接字 ID。

要获取套接字 id,请使用socket.id

var chat = io.of("/socket").on('connection',onSocketConnected);

function onSocketConnected(socket){
   console.log("connected :"+socket.id);  
}
于 2014-12-31T12:00:34.963 回答
6

如果您使用了命名空间,我发现以下方法有效:

//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/

于 2015-04-01T13:55:01.040 回答
5

我相信@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
于 2016-10-18T19:23:51.577 回答
1

在 Node.js --> socket.io --> 有一个聊天示例可以下载 将其粘贴到行中(io on connection)部分.. 我使用的代码可以 100% 工作

io.on('connection', function(socket){
  socket.on('chat message', function(msg){
    console.log(socket.id);
    io.to(socket.id).emit('chat message', msg+' you ID is:'+socket.id);
  });
});
于 2017-12-17T12:54:10.400 回答
0

更新 Socket.io v4.0+

var socketById = io.sockets.sockets.get(id);
socketById.emit("message", "hi")

这是在 v4 中通过 ID 获取套接字并向其发射的最佳方式。

于 2021-10-15T13:48:28.930 回答