我有一个演示设置:
但它无法连接。Nginx日志显示:
更新:我刚刚发现了这个很好的解释(socket.io/docs/client-api/),为什么它不起作用:
这个小小的斜杠
node.js WebSocket服务器#1(使用'socket.io')运行在端口8001上
node.js WebSocket服务器#2(使用'socket.io')运行在端口8002上
nginx websocket反向代理运行在端口8000上:
重定向任何请求到/wstest1/到端口8001(服务器#1) 重定向任何请求到/wstest2/到端口8002(服务器#2)
一个node.js客户端(使用'socket.io-client',而不是浏览器JavaScript客户端)试图连接到服务器#1:
var socket = require('socket.io-client')('ws://localhost:8000/wstest1/');
但它无法连接。Nginx日志显示:
127.0.0.1 - - [06/Feb/2015:16:16:04 +0100] "GET /socket.io/?EIO=3&transport=polling&t=1423235764132-1&b64=1 HTTP/1.1" 404 168 "-" "node-XMLHttpRequest"
所以某处丢失了到/wstest1/
的路径。
/wstest1/
nginx设置:
http {
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
listen 8000;
location /wstest1/ {
proxy_pass http://localhost:8001;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
location /wstest2/ {
proxy_pass http://localhost:8002;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
}
更新:我刚刚发现了这个很好的解释(socket.io/docs/client-api/),为什么它不起作用:
返回指定路径名字空间的Socket实例,如果没有指定则默认返回“/”。例如,如果URL是http://localhost/users,则会建立一个传输连接到http://localhost,并建立一个Socket.IO连接到/users。
有什么解决方法吗?
可耻的我。典型的RTFM / RTFC(C代表代码)案例:
解决方案:
使用正确的路径:
var socket = require('socket.io-client')('ws://localhost:8000', {path: '/wstest1/socket.io'});
使用正确的nginx配置:
proxy_pass http://localhost:8001/;
这个小小的斜杠
/
有很大的区别。