我在精确的 64 vagrant box 上使用 Nginx + Websockets,并使用 c#/mono 作为应用程序服务器。目标是直接通过 Nginx 提供静态内容,并在同一端口上处理普通的 http 服务请求(在 /service 上)和 websocket 请求(在 /webSocket 上)。这是相关的配置:
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
listen 80 default_server;
# (1)
location / {
root /var/www;
index index.html;
}
# (2)
location /service {
add_header Access-Control-Allow-Origin *;
proxy_pass http://localhost:9000;
}
# (3)
location /webSocket {
proxy_pass http://localhost:9000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
}
}
大部分都运行良好。静态内容,是的,服务请求,是的,甚至是 websockets 的第一部分。我从我的客户端(Firefox 或 Chrome)收到格式正确的 101 切换协议请求。我正在制作一个很好的 http 升级响应并发送它。然后客户什么也没做……什么也没有收到。
但疯狂的是,当我放弃并手动终止我的服务器端应用程序,并且客户端 Web 套接字因错误关闭时,响应标头就会显示在客户端浏览器调试器上。整个事情看起来像:
REQUEST HEADERS
Request URL: http://localhost:8086/webSocket
Request Method: GET
Status Code: HTTP/1.1 101 Switching Protocols
Request Headers 16:18:50.000
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0
Upgrade: websocket
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: Nx0sUAemOFWM2rsaCAJpfQ==
Sec-WebSocket-Extensions: permessage-deflate
Pragma: no-cache
Origin: http://localhost:8086
Host: localhost:8086
Connection: keep-alive, Upgrade
Cache-Control: no-cache
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
RESPONSE HEADERS Δ19660ms
Upgrade: websocket
Transfer-Encoding: chunked
Server: nginx/1.1.19
Sec-WebSocket-Accept: gNiAeqxcVjkiReIpdtP0EZiClpg=
Date: Mon, 08 Jun 2015 20:18:48 GMT
Connection: keep-alive
NO RESPONSE BODY Δ0ms
没有证据表明我的服务器应用程序没有立即刷新其发送数据 - 我正在使用异步 TcpSocket.BeginSend 和 FinishSend 并且发送似乎立即完成。它在普通的 http 服务通信上工作得很好。
那么我的 websocket 消息数据去哪里了???看起来 Nginx 不想将其发送回我的客户端,除非我从服务器端关闭 Tcp 连接。
有没有人经历过类似的事情。我读到的关于 Nginx 和 Websockets 的所有内容都与使逐跳升级正常工作的基本设置有关,我已经了解了。没有人可以解释为什么从服务器端发回的消息似乎没有到达任何地方。