使用 socket.io 和 node.js 向特定客户端发送消息

问题描述:

我正在使用 socket.io 和 node.js,直到现在看起来还不错,但我不知道如何从服务器向特定客户端发送消息,如下所示:

I'm working with socket.io and node.js and until now it seems pretty good, but I don't know how to send a message from the server to an specific client, something like this:

client.send(message, receiverSessionId)

但是 .send().broadcast() 方法似乎都不能满足我的需要.

But neither the .send() nor the .broadcast() methods seem to supply my need.

我发现一个可能的解决方案是 .broadcast() 方法接受一个不向其发送消息的 SessionIds 数组作为第二个参数,因此我可以传递一个数组当时连接到服务器的所有SessionId,除了我希望发送消息的那个,但我觉得必须有更好的解决方案.

What I have found as a possible solution, is that the .broadcast() method accepts as a second parameter an array of SessionIds to which not send the message, so I could pass an array with all the SessionIds connected at that moment to the server, except the one I wish send the message, but I feel there must be a better solution.

有什么想法吗?

好吧,您必须为此抓住客户(惊喜),您可以选择简单的方法:

Well you have to grab the client for that (surprise), you can either go the simple way:

var io = io.listen(server);
io.clients[sessionID].send()

这可能会中断,我对此表示怀疑,但 io.clients 总是有可能被更改,因此请谨慎使用上述内容

Which may break, I doubt it, but it's always a possibility that io.clients might get changed, so use the above with caution

或者您自己跟踪客户端,因此您将它们添加到 connection 侦听器中的您自己的 clients 对象中,并在 disconnect中删除它们代码>监听器.

Or you keep track of the clients yourself, therefore you add them to your own clients object in the connection listener and remove them in the disconnect listener.

我会使用后一种,因为根据您的应用程序,无论如何您可能希望在客户端上拥有更多状态,因此类似于 clients[id] = {conn: clientConnect, data: {...}} 可能会完成这项工作.

I would use the latter one, since depending on your application you might want to have more state on the clients anyway, so something like clients[id] = {conn: clientConnect, data: {...}} might do the job.