3

I am using node.js and socket.io for some two way data handling. What I want is persistent connections when the client navigates through the site. I was using standard

var socket;
socket = io.connect("http://localhost:port");
socket.on('connect', function(data){
    console.log("called connect");
    console.log(user_id);
    socket.emit('init', user_id);
});

This way I assign the user_id to that socket and can use that later to send data selectively to certain users. I was first inserting this in every web page. I notice that socket connect and disconnect is called when we move to new page and even on reloads. Is there a way to avoid this and do the init call only once?

I tried looking at express.js but couldn't figure out any obvious solutions.

Naveen Sharma
  • 1,057
  • 12
  • 32
  • You can't. What you can do is not actually load a new page, but load the new content via `AJAX` on the same page. You can also, if you want, keep your socket on the current page and have all content load in an `iframe` instead. – XCS Aug 06 '14 at 08:49
  • @Cristy, can i run two node processes on same port and serve different pages through different node processes? – Naveen Sharma Aug 06 '14 at 09:49

2 Answers2

3

Yes, it is called a single page application. The idea is to not reload the page or send pages through separate HTTP requests. Instead, use WebSockets to simply get the data necessary to render what the user wants to see. The main advantage of single page apps is that you always stay in control and the entire browsing experience can be much smoother.

There are many frameworks out there that make front-end development for single page applications easier. The more popular ones are probably Angular and Ember.

Of course you don't need WebSockets to create single page apps. You can just use Ajax requests for that as well. However, WebSockets offer other advantages.

Load-balancing WebSockets can be trickier than traditional HTTP or Ajax requests, but guessing from your question, that is probably not an issue to you, as of yet.

Community
  • 1
  • 1
Domi
  • 22,151
  • 15
  • 92
  • 122
0

You could try to store the socket.id in your directory and instead of creating a new socket again when the user goes to a new page it just uses the first one created by pulling it from your directory.

Check this out: how do I store socket resources from specific users with socket.io?

Community
  • 1
  • 1
Craig
  • 1,065
  • 3
  • 12
  • 26