nodejs socketio多个域(单独的io)

时间:2016-02-04 01:19:08

标签: node.js express socket.io vhosts express-vhost

我创建了两个使用socketio + nodejs的网站(+ 2个dev网站)。 现在,我需要将2个站点移动到一个服务器中。

要做到这一点,我使用了express-vhost,它适用于所有东西......除了socket.io。

在我的应用程序中,我使用了数百次以下功能。 socket.emit(), io.sockets.emit() , socket.broadcast.emit()等等。 当我创建网站时,我第一次使用socketio,并且正在学习它。因此,我从未使用名称空间(仍未使用它们)。

现在,当我在vhost下运行这两个站点,并且有人连接到site1时,它们也连接到site2,因为它们使用相同的socket.io实例。

所以,我尝试创建多个socketio实例,每个域一个,如此

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.

这几乎似乎有用......但是,只要我为socketio创建了第二个实例(服务器),那么之前创建的实例就会“断开连接”并停止工作。

我如何创建socketio服务器的多个实例并让它们独立工作。或者,我怎么能解决这个问题...也许使用命名空间(我还不知道如何使用它们)。

1 个答案:

答案 0 :(得分:0)

很难回答,这取决于您的服务器代码, 但这可能会帮助您找到解决方案......

[1]唯一的socket.io实例(使用命名空间):

您必须找到实施它的最佳方式......

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');
});

编辑:此选项是为了您想要来自domain_a&的客户端。 domain_b在它们之间进行通信

[2] Independent node.js services:

在端口80上使用node.js和 node-http-proxy 作为其他node.js服务的路由器。

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);

...或者你可以试试......
NGINX https://www.nginx.com/blog/nginx-nodejs-websockets-socketio/

祝你好好实施。

相关问题