简体   繁体   English

Socket.io:发送到指定的客户端

[英]Socket.io: Emit to specified Clients

I have a node.js/socket.io webapp that is currently working correctly polling an API and populating the html page with the emitted results. 我有一个node.js / socket.io网络应用程序,当前正在正确轮询API并使用发出的结果填充html页面。

My problem is that multiple people need to use this and I would like to separate their instances so that each person will only receive the results of their query. 我的问题是,需要使用多个用户,并且我想分开他们的实例,以便每个人都只会收到他们的查询结果。

Right now, when anyone uses the site it will return results of another user that may be also using the site. 现在,当任何人使用该网站时,它将返回另一个可能也在使用该网站的用户的结果。 I have tried to get around this using this method: 我试图使用这种方法来解决这个问题:

var clients = {};
 io.sockets.on('connection', function(socket){
    console.log("this is "+socket.id);
    clients.id = socket.id;
 })

io.sockets.socket(clients.id).emit('progress',{info:listing});

Of course this gets replaced with each new user that logs into the site so then everything that was emitted to the original user is now being emitted to the new user. 当然,这将由登录该站点的每个新用户替换,因此,发给原始用户的所有内容现在都将发给新用户。

What I want to know is if there is any built-in function to get around this or if I should proceed with another persistent store. 我想知道的是是否有内置函数可以解决此问题,或者我是否应该继续使用另一个持久存储。

Any help would be greatly appreciated. 任何帮助将不胜感激。

Edit 编辑

By storing the socket object in the express.sessionStore instead of just in the program. 通过将套接字对象存储在express.sessionStore中而不是仅存储在程序中。 io.sockets.on(function(socket){ request.sessionStore.socket = socket; })

The above code now works and only emits to the event originator. 上面的代码现在可以正常工作,并且仅向事件发起者发出。

This looks like it's been answered in another thread. 看起来好像已经在另一个线程中得到了回答。 The idea is to create an array of clients, and associated it to some type of client/user identification, like an ID or name. 这个想法是创建一个客户端数组,并将其与某种类型的客户端/用户标识(例如ID或名称)相关联。

Sending a message to a client via its socket.id 通过socket.id向客户端发送消息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM