Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Channels using sockjs (node.js, socket.io)

It came to my attention that socket.io has a lot of issues(memory leaks, CPU usage etc), therefore I am converting my application to sockjs(or something else..if this turns to be difficult to implement).

In socket.io I was able to easily emmit messages on several "cahnnels" using the same connection

socket.emit('news', { hello: 'world' });
socket.emit('other', { hello: 'world' });

How can I achieve this using sockjs? I understand that this functionallyt has not been implemented in sockjs, but is there a reliable framework that does this? I run into this websocket-multiplex but wasn't satisfied with the reviews that I read on several blogs.

Thank you

like image 216
gumenimeda Avatar asked Jan 11 '23 14:01

gumenimeda


1 Answers

I really like the direction the team over at the primus library is taking because there is so much churn in socket implementations right now. They allow you to freely switch between several of the most popular websocket libraries (including sockJS) with no additional code.

You could use primus with the community plugin rooms to accomplish what you are trying to do.

The plugin would allow you to do something like this:

spark.room('news').write( { hello : 'world' } );

A spark works almost the same way as a socket. Whenever primus receives a connection, it gives you a spark object to manipulate. So, here's a complete example:

var Primus = require('primus')
  , http = require('http');

var server = http.createServer(/* request handler */)
  , primus = new Primus(server, { transformer: 'sockjs' });

primus.on('connection', function (spark) {
  spark.room('news').write( { hello : 'world' } );
});

Please note that there are a few caveats to using sockJS with primus. The caveats won't affect your situation as you have described it.

Personally, I've had success with the good old ws library combined with primus to get these nice features. It gives you RFC 6455 compliant sockets which helps when trying to connect to clients on multiple platforms.

Update 0 that is in response to a question in the comments about filtering rooms on client-side, follows:

First, according to the documentation for client-side usage of primus, you'll need to access the primus client-side API. For development usage, a route is automatically added to your http server such that you can do the following in your html:

// use this to load the client-side framework in development only
<script src="/primus/primus.js"></script>

Then, take a look at the linked documentation for what you need to do in production to support the case where you need access to the primus library on the client.

Second, poke around in the primus-rooms client / server examples to see how to set things up. You can use this method to broadcast a message to a specific room.

like image 164
ctlacko Avatar answered Jan 18 '23 06:01

ctlacko