2

It's pretty easy to configure a http server (using express) and a socket server (socket.io) assigned to it:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

How can I run http server and socket server in two different node.js instances?

My idea is to leverage the performance this way, releasing the http node instance from the responsibility of also sending notifications back to the clients.

Aleks
  • 5,674
  • 1
  • 28
  • 54
  • Run two different processes? – freakish Jul 07 '14 at 05:45
  • Yes. Besides those two, I would run one node instance more, as a backend, serving a DB contents to http server and (when needed) notifications to the sockets server. – Aleks Jul 07 '14 at 05:48

1 Answers1

1

In a regular Socket.IO + Express app, Socket.IO intercepts requests starting with /socket.io/.

You may set Nginx (or any other webserver that supports proxying) listening 80 port, and make it proxy to Socket.IO process if request starts with /socket.io/, and to Express process otherwise.

Edit: To set up Socket.IO in separate process you may use the following code:

var io = require('socket.io')();
io.on('connection', function(socket){
    //here you can emit and listen messages
});
io.listen(3000);
Oleg
  • 22,300
  • 9
  • 68
  • 84
  • Thank you, it makes sense... In order this to work, how can I "pass" the io object to this other process (that's my main problem)? Please see the code snippet from the question - both http (express) and io (socket.io) servers are created in the same Node-instance. I need to have two Node instances running those servers. Other way around would be to initially create express server and socket.io on separate node-instances. Is this possible? – Aleks Jul 07 '14 at 07:53
  • Unfortunately, you can't pass an object to different process the way you pass object to a function. I think you have to implement something like inter-process messaging. Take a look at [this topic](http://stackoverflow.com/questions/6463945/whats-the-most-efficient-node-js-inter-process-communication-library-method), it might be helpful to you. – Oleg Jul 07 '14 at 08:00
  • "create express server and socket.io on separate node-instances. Is this possible?" - yes, this is possible. Take a look at my edit – Oleg Jul 07 '14 at 08:22
  • If I understood well, the idea is to start express server from the first node instance and then, independently socket.io server from the second instance (socket.io will create its own http server which will be "invisible" for me). Is this right? – Aleks Jul 07 '14 at 13:16
  • Yes, you are right except the socket.io server will not be invisible. It will be accessible if the request starts with `/socket.io/`. You will have to set up nginx so that it will proxy such requests to socket.io server. – Oleg Jul 07 '14 at 13:38