nodejs socketio multiple domains( separate io )

1.5k Views Asked by At

I have created 2 websites, that use socketio+nodejs( + 2 dev sites for them ). Now, i need to move the 2 sites into one server.

To do that, i used express-vhost, and it works for everything...except for socket.io.

In my apps, i have used hundreds of times the following functions. socket.emit(), io.sockets.emit() , socket.broadcast.emit() and so on. When i created the sites, i was using the socketio for the first time, and was learning it. Thus, i never used namespaces( still havent used them ).

Now, when i run both sites under vhost, and someone connects to site1, they also connect to site2, because they use the same socket.io instance.

So, i tried to create multiple instances of socketio, one for each domain, like so

http = server.listen(80);//my vhost main app

global.io_for_domain_1 = require('socket.io')(http, {'transports': ['websocket', 'polling']} );

global.io_for_domain_2 = require('socket.io')(http, {'transports': ['websocket', 'polling']} );

/*And then, in my domain app, i was hoping to simply swap out the reference for io like so
...in my global socket controller that passes io reference to all other controllers...*/
this.io = global.io_for_domain_1 ;
//hoping that this would help me to avoid not having to re-write the hundreds of references that use io.

This almost seemed to work...But, as soon as i create the second instance(server) for socketio, the ones that were created before get "disconnected" and stop working.

How could i create multiple instances of socketio server and have them work independently. Or, how else could i solve this problem...perhaps using namespaces( i still dont know exactly how to use them ).

1

There are 1 best solutions below

0
On BEST ANSWER

Its hard to answer, it depends on your server code, but this might help you find a solution...

[1] Unique socket.io instance (using namespaces) :

You would have to find the best way of implementing it...

var domain_a = io.of('/domain_a');
var domain_b = io.of('/domain_b');

domain_a.on('domainA_clientAction', function(socket){
    domain_a.emit('domainA_clientAction');
});

domain_b.on('domainB_clientAction', function(socket){
    domain_b.emit('domainB_serverResponse');
});

EDIT: This option is in case you want clients from domain_a & domain_b communicate between them

[2] Independent node.js services :

Using a node.js with node-http-proxy on port 80 as a router for other node.js services.

var http = require('http')
, httpProxy = require('http-proxy');

httpProxy.createServer({
  hostnameOnly: true,
  router: {
    'domain-a.com': '127.0.0.1:3001',
    'domain-b.com': '127.0.0.1:3002'
  }
}).listen(80);

... or maybe you can try with ...
NGINX https://www.nginx.com/blog/nginx-nodejs-websockets-socketio/

Good luck with your implementation.