Socket.IO on subdomains with Express.js vhost

笑着哭i 提交于 2019-12-21 06:24:42

问题


I have two Express.js apps running on my server.

A plain vanilla app called "main-app" and another that uses Socket.IO called "socket-app".

I have "main-app" running at "mydomain.com" & "socket-app" running on a subdomain at "socket.mydomain.com"

I am routing requests to the socket-app via Express's built-in vhost middleware.

-- inside main-app.js --

var express = require('express');
var app = module.exports = express.createServer();
app.use(express.vhost('socket.mydomain', require('./socket-app/app.js')));

app.listen(8080, function(){
  console.log("Express server listening on port %d in %s mode");
});

This works fine and I can see my socket-app running on port 8080 at socket.mydomain

However, there seems to be a problem with websockets timing out and not receiving the "upgrade" event when running a Socket.IO app through vhost as discussed here.

So my question is how can I pipe this "upgrade" event from my main-app to my socket-app so all connected sockets can hear when someone connects & disconnects?

I've tried emitting the "upgrade" event from within "main-app" but it doesn't appear to be working.

app.on('upgrade', function(req, socket) {
    socket.emit('upgrade', app);    
});

What am I missing here?


回答1:


The solution is to create one instance of Socket.IO in your root application that can be globally accessed by your subdomain applications and then run each app in its own Socket.IO namespace to preserve their autonomy.

I just built a simple example that runs three instances of a chat application all sharing the same instance of Socket.IO, which is declared in the root application.

If you clone the project and follow the instructions to set up the local subdomains you can see each instance of the chat application running independent of the others.

I will try to write up blog post with further details about how it works tomorrow morning.

Update

Here's a write up of how to share a Socket.IO instance across multiple domains.



来源:https://stackoverflow.com/questions/10674884/socket-io-on-subdomains-with-express-js-vhost

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!