nodejs socketio多个域(单独的io)

我创build了2个网站,使用socketio + nodejs(+ 2开发网站)。 现在,我需要将这两个网站移到一个服务器上。

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

在我的应用程序中,我使用了几百次以下的函数。 socket.emit(), io.sockets.emit() , socket.broadcast.emit()等等。 当我创build网站,我第一次使用socketio,并正在学习它。 因此,我从来没有使用名称空间(还没有使用它们)。

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

所以,我试图创buildsocketio的多个实例,每个域的一个,像这样

 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. 

这似乎工作…但是,只要我创build了第二个实例(服务器)的socketio,那些之前创build的“断开”,并停止工作。

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

它很难回答,这取决于您的服务器代码,但这可能会帮助您find一个解决scheme…

[1]独特的socket.io实例(使用名称空间):

你将不得不find实施它的最好方法…

 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]独立的node.js服务:

在端口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/

祝你好运。