Change Socket.IO static file serving path

2019-02-01 23:00发布

问题:

I am using Socket.IO on a Node server with a basic HTTP server (no Express or Connect or anything like that). By default, Socket.IO serves the client file to

/socket.io/socket.io.js

I would like to be able to change that base path to something else, like

/foo/bar/socket.io/socket.io.js

Is there any built-in way to do this, or any way without changing Socket.IO's code? I think the answer lies in the Static module (require('socket.io').Static)), but short of writing my own to replace the default, I see no way to go and change the way that behaves.

How can I do this?

回答1:

The resource option allows you to configure socket.io's root directory. It defaults to /socket.io.

var io = require('socket.io').listen(app, { resource: '/foo/bar/socket.io' });

Note that this setting also affects where socket.io's endpoints are served from, so you must also change this setting in your client code.

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

(Note we don't use a leading slash here for some reason.)



回答2:

For socket.io version 1.2.1, this works for me.

Server side:

var io = require('socket.io')({path: '/foo/bar'});

Client side:

var socket = io.connect('http://example.com', {path: '/foo/bar'});

FYI: http://socket.io/docs/migrating-from-0-9/#configuration-differences



回答3:

If you are using socket.io version 1.0, the configuration is different than in previous versions.

For client side:

var socket = io.connect('http://localhost:8888', { path: '/some/path/socket.io' });

For server side

    var socket = require("socket.io")( { resource: '/some/path/socket.io' });


回答4:

You can find the client side script socket.io.js in the path node_modules/socket.io/node_modules/socket.io-client/dist. Copy it to a new folder and call it with the correct path from the client

<script src="/your/path/to/socket.io.js"></script>

For more configuration visit the wiki