Reputation: 845
I've looked around for an answer regarding this question, I am not sure if I am going about this the right way.
I have a node.js application that uses socket.io to push and receive data from the node server to the client. Most of the requests sent to nodejs are through HTTP Requests while the data pushed to the website is received through a socket.
I currently have unique namespaces for each of the individual listeners (for example I have a feed with comments, this means I have feed/{ID} as the listener as well as each comment has comment/{COMMENTID}. This means if there are 25 feed posts, I would have 26 (including the feed) listeners listening for the feed alone.
I am not entirely sure how socket.io pushes data through the listeners (is each listener a new socket?). In my mind, if I have a large amount of users online at one point and a single comments listener it will be hit many times with useless, unrelated data - in comparison to now where it will only receive data relevant to the user.
What is the best way to set up the listeners?
Is more or less listeners beneficial?
Upvotes: 6
Views: 12110
Reputation: 818
You should use Rooms to handle this. Each time a user is viewing a feed page, it register to a room and then you push only the relevant information to users based on the page they are actually seeing.
socket.on('subscribe', function(data) { socket.join(data.room); });
socket.on('unsubscribe', function(data) { socket.leave(data.room); });
then when you want to send information to a specific room
io.sockets.in('feed_1').emit('comment', data);
You can see the documentation here: https://github.com/LearnBoost/socket.io/wiki/Rooms
Upvotes: 4
Reputation: 791
That's a bad way to use listener. You should use just
When you want to send data to feed listener, use "socket.emit('feed',{id:1})". When you want to send data to comment listener, use "socket.emit('comment',{commentid:1})"
This will reduce you to just 2 listener.
Upvotes: 5