How do I get socket.io running for a subdirectory

风格不统一 提交于 2019-12-03 11:36:22

问题


I've got a proxy running that only hits my node.js server for paths that being with /mysubdir How do I get socket.io configured for this situation?

In my client code I tried:

var socket = io.connect('http://www.example.com/mysubdir');

but then I notice that the underlying socket.io (or engine.io) http requests are hitting

http://www.example.com/socket.io/?EIO=3&transport=polling&t=1410972713498-72`

I want them to hit

http://www.example.com/mysubdir/socket.io.....

Is there something I have to configure on the client and the server?


回答1:


In my server I had to

var io = require('socket.io')(httpServer, {path: '/mysubdir/socket.io'})`

In my client I had to

<script src="http://www.example.com/mysubdir/socket.io/socket.io.js"></script>

and also

var socket = io.connect('http://www.example.com', {path: "/mysubdir/socket.io"});`



回答2:


In my case I am using nginx as a reverse proxy. I was getting 404 errors when polling. This was the solution for me.

The url to the node server is https://example.com/subdir/

In the app.js I instantiated the io server with

var io = require('socket.io')(http, {path: '/subdir/socket.io'});

In the html I used

socket = io.connect('https://example.com/subdir/', {
    path: "/subdir"
});

Cheers,
Luke.




回答3:


The answer by @Drew-LeSueur is correct for socket.io >= 1.0.

As I was using socket.io 0.9, I found the old way of doing it in the doc.

// in 0.9
var socket = io.connect('localhost:3000', {
  'resource': 'path/to/socket.io';
});

// in 1.0
var socket = io.connect('localhost:3000', {
  'path': '/path/to/socket.io';
});

Notice that a / appears as first character in the new path option.




回答4:


Using nginx, this a solution without the need to change anything in the socket.io server app:

In the nginx conf:

location /mysubdir {
   rewrite ^/mysubdir/(.*) /socket.io/$1 break;
   proxy_set_header Upgrade $http_upgrade;
   proxy_set_header Connection "upgrade";
   proxy_http_version 1.1;
   proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
   proxy_set_header Host $host;
   proxy_pass http://127.0.1.1:3000;
}

In the server:

var io = require('socket.io')(3000)

In the client:

var socket = io.connect('https://example.com/', {
    path: "/mysubdir"
})


来源:https://stackoverflow.com/questions/25896225/how-do-i-get-socket-io-running-for-a-subdirectory

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