Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use socket.io only on specific page in my website?

Let's suppose I have a website that DOESN'T require web-sockets on the home page, but DOES require it on some other relative path ('/new' for example).

Suppose I need the 'connection' event in order to count users that login to the 'home' page and to the 'new' page.

I've tried to configure socket.io 'connection' event in the relative path like:

app.get('/new',
         function(req,res) {
              io.sockets.on('connection', function (socket) {
                .....
              }
         });

BUT:

  1. It doesn't perform well. When a lot of users connected, that event gets raised when it shouldn't.
  2. I didn't see any example on the web like the one above. All of the socket.io events are configured in the main file (app.js) once.

How can it be done ?

like image 619
ohadinho Avatar asked Aug 01 '13 08:08

ohadinho


1 Answers

Answering your questions:

  1. Obviously, because when a user hits /new its handler fires and adds connection handler to io. It's a huge memory leak.

  2. That's related to the one above. You don't want to add a connection handler every time a user hits /new.

Now to solve your problem I think that the best idea is to call (on the browser side)

io.connect("http://localhost/new");

and then in your Node.js app:

io.of("/new").on("connection", function (socket) {
    // here are connections from /new
});

The code should be placed at the top level, not inside a route handler. If you want it to be more dynamic, then you can create your own sub-protocol:

  1. Connect to the io server: io.connect("http://localhost);
  2. Send a message I'm in /new;
  3. On the server get that message and store that connection in an appropriate list.

Of course you can specify in your route handler whether you want your client to connect to socket.io server or not (simply by passing some kind of flag).

like image 75
freakish Avatar answered Oct 14 '22 01:10

freakish