Using socket.io with nodejs on a server with apache as a reverse proxy

node.js, reverse-proxy, socket.io

Solution

This ended up being a multi-pronged solutions.

First, on the server end of things, I had to set up the endpoints like this

var io = require('socket.io').listen(8080);

var rootSockets = io.of('/nodejs').on('connection', function(socket)
{
  // stuff
});

var otherSockets = io.of('nodejs/other').on('connection', function(socket)
{
  // stuff
});

Then, on the client-side, to properly connect looks like this

var socket = io.connect(
    'http://example.com/nodejs/'
  , {resource: 'nodejs/socket.io'}
);

// The usage of .of() is important
socket.of('/nodejs').on( 'event', function(){} );
socket.of('/nodejs/other').on( 'event', function(){} );

After this, it all worked. Remember, on this server Apache is proxying example.com/nodejs to port 8080 internally.

Problem

I'm attempting to use Node.js with Socket.IO to faciliate messaging between the browser and client, following the guide. However, I had to setup Node reverse-proxied behind Apache. So, instead of example.com:8080 for node, I'm using example.com/nodejs/. This seems to cause Socket.IO to lose sense of itself. Here's my node app ``` var io = require('socket.io').listen(8080); // this has to be here, otherwise the client tries to // send events to example.com/socket.io instead of example.com/nodejs/socket.io io.set( 'resource', '/nodejs/socket.io' ); io.sockets.on('connection', function (socket) { socket.emit('bar', { one: '1'}); socket.on('foo', function( data ) { console.log( data ); }); }); ``` And here's what my client file looks like ``` <!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title>Socket.IO test</title> <script src="http://example.com/nodejs/socket.io/socket.io.js"></script> <script> var socket = io.connect('http://example.com/nodejs/'); console.log( socket ); socket.on( 'bar', function (data) { console.log(data); socket.emit( 'foo', {bar:'baz'} ); }); socket.emit('foo',{bar:'baz'}); </script> </head> <body> <p id="hello">Hello World</p> </body> </html> ``` The problem here is the script reference to http://example.com/nodejs/socket.io/socket.io.js. It doesn't return the expected javasscript content - instead it returns "Welcome to socket.io" as if I hit http://example.com/nodejs/. Any idea how I can make this work?

Original source

Related problems