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?
emit() doesn't have any magical powers, it just loops through all the current connected clients and calls socket. emit() for each one individually using their particular socket object - saving you the work of having to write that code yourself. From the client, socket. emit() will send a message to the server.
Socket.IO is way more than just a layer above WebSockets, it has different semantics (marks messages with name), and does failovers to different protocols, as well has heartbeating mechanism. More to that attaches ID's to clients on server side, and more.
Although Socket.IO indeed uses WebSocket for transport when possible, it adds additional metadata to each packet. That is why a WebSocket client will not be able to successfully connect to a Socket.IO server, and a Socket.IO client will not be able to connect to a plain WebSocket server either.
Server was able to handle 100000 events distributed in 1000 rooms with 5 requests per second querying db.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With