用socket.io-client连接到URL

我有这个演示设置:

  • 在端口8001上运行的node.js WebSocket服务器#1(使用'socket.io')

  • 在端口8002上运行的node.js WebSocket服务器#2(使用'socket.io')

  • 运行在端口8000上的nginx websocket反向代理:

    将任何请求redirect到/ wstest1 /到端口8001(服务器#1)

    将任何请求redirect到/ 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" 

所以某处path/wstest1/丢失了。

我怎么能告诉socket.io客户端它应该连接到/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/),为什么它不起作用:

返回由URL中的path名指定的名称空间的Socket实例,默认为/。 例如,如果url是http:// localhost / users ,则将build立到http:// localhost的传输连接,并将为/ usersbuild立一个Socket.IO连接。

任何解决方法?



对我感到羞耻。 RTFM / RTFC经典案例(C代码):

解:

使用正确的path:

 var socket = require('socket.io-client')('ws://localhost:8000', {path: '/wstest1/socket.io'}); 

使用正确的nginxconfiguration:

 proxy_pass http://localhost:8001/; 

这个小尾随/有所作为。

在/etc/nginx/nginx.conf中设置位置

 location /wstest1 { proxy_pass http://localhost:8001; } location /wstest2 { proxy_pass http://localhost:8002; } 

查看更多: http : //nginx.org/en/docs/http/ngx_http_core_module.html#location

请参阅http://socket.io/docs/rooms-and-namespaces/上的文档。

重要说明:名称空间是Socket.IO协议的实现细节,与底层传输的实际URL无关,默认为/socket.io/…。

如果你想让你的socket.io端点在'/ wstest1'或'/ wstest2'托pipe,只需在创build服务器时将其作为“path”parameter passing。