使用 socket.io 和 node.js 向特定客户端发送消息 [英] Send message to specific client with socket.io and node.js

查看:53
本文介绍了使用 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.

这篇关于使用 socket.io 和 node.js 向特定客户端发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆