简体   繁体   English

Node js连接两个套接字,以便检索将更容易

[英]Node js connecting two socket so that retrieving would be easier

Currently now i am using io.emit where i send the event to all the connected users and in client side i check whether the id of user i emit is equal to the id of client side then the condition runs i thinks its making my code messy and bit slow is there anything i can do like connecting then in one group so when retrieving them i would be easier for me. 目前,我现在正在使用io.emit将事件发送给所有连接的用户,在客户端,我检查发出的用户ID是否等于客户端的ID,然后条件运行,我认为这使我的代码混乱而且有点慢,我可以像在一组中进行连接一样进行任何操作,所以在检索它们时我会更轻松。

//server side
var id = 1;
io.emit('check',id);

// on client side 
socket.on('check',function(data){
var current_user_login = //getting current user login id by php
if(data == current_user_login) { 
//run some code
}
});

If you want to put certain sockets in the same room, so that it's easy to broadcast to all of them together. 如果要在同一房间中放置某些插座,以方便将它们一起广播。 Try this: 尝试这个:

var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) {
  socket.join('group');
  socket.broadcast.to('group').emit('new member');
});

Hope this helps. 希望这可以帮助。

The better way to solve this problem is to create an association between the user you want to send the data to and that user's socket so you can .emit() only to that particular socket. 解决此问题的更好方法是在要向其发送数据的用户和该用户的套接字之间创建关联,这样您就可以仅.emit()到该特定套接字。 This is much, much more efficient than sending to everyone especially when you have lots of connected sockets. 这比发送给所有人的效率要高得多,尤其是当您有大量连接的套接字时。

You would have to explain to us much more about how you know which socket or user you want to send to in order for us to help figure out how to do that association in your server. 您将不得不向我们解释更多有关如何知道要发送给哪个套接字或用户的信息,以帮助我们确定如何在服务器中进行该关联。

socket.io has the concept of "rooms" which are groups of sockets that makes it easy for you to place a socket in a specific group and to then broadcast to a specific group of sockets. socket.io具有“房间”的概念,它们是一组插座,使您可以轻松地将一个插座放入特定的组中,然后广播到特定的一组插座。

Or, each socket has an id and each socket has access to the cookies that were present when the connection was first made, both of which can sometimes be used to identify which user you want to send to. 或者,每个套接字都有一个id,并且每个套接字都可以访问首次建立连接时存在的cookie,有时这两个cookie都可以用来标识您要发送给哪个用户。 But, you'd have to explain how you know which user you want to send to for us to help give you an idea how to code that into your server. 但是,您必须解释一下您如何知道要发送给哪个用户,以帮助我们了解如何将其编码到服务器中。

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

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