简体   繁体   中英

Socket.IO on subdomains with Express.js vhost

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM