Accessing socket.io server via Apache served pages

2020-04-02 16:55发布

问题:

I hope this doesn't come across as a terribly silly question, but I'm learning how to implement a socket.io server for my website to produce real-time applications, but my problem is that I can't figure out how to implement said applications in an Apache served environment. Currently, when I run node server.js to start my socket.io server, I have to access it by visiting http://localhost:XXXX where XXXX is whatever port I attach it to, naturally. I don't want my website to be forced to be viewed on an alternate port like this, but I obviously can't attach the server to port 80 since Apache is listening on that.

Obviously a natural solution would be to stop the Apache service and then node the server on port 80 that way to avoid a collision, but I don't want to sacrifice all of the functionality that Apache offers. Basically, I want to continue to serve my website via Apache on port 80, and integrate certain aspects of real-time applications via socket.io on port 3000, let's say.

Is there a way to do this that avoid the things I don't want? Those things being 1) having users access my site with :3000 in the URL, 2) disabling Apache, 3) using iframes.

Thanks in advance.

回答1:

Generally, you should be able to hide Node.js with mod_proxy. A bit of searching turned up this: https://github.com/sindresorhus/guides/blob/master/run-node-server-alongside-apache.md (old link died, this is a new one)

However, Socket.io can be a bit finicky (https://github.com/LearnBoost/socket.io/issues/25), so you may have problems with it specifically.

As that ticket is a bit old, it's worth a shot. Just don't be surprised if you have problems. You're next bet after that is bind Node.js toport 80 and have it act as a reverse proxy for Apache with https://github.com/nodejitsu/node-http-proxy (still under a fair bit of development).

The optimal solution would be run it on it's own server and just have you're socket traffic go to socket.example.com or something like that.



回答2:

Socket.io has multiple transport mechanisms. Some of them don't work if you run Apache as reverse proxy, but some do. Transports that don't work are websocket and flash, but xhr-polling and jsonp-polling should work.

Here's an example on setting the transports configuration option for socket.io:

var io = require("socket.io").listen(server);
io.set("transports", ["xhr-polling", "jsonp-polling"]);

On my Apache I'm using the normal name based virtual hosts and reverse proxy setup and with these transports the socket.io seems to be working.