Socket.io与Nginx [英] Socket.io with nginx

查看:282
本文介绍了Socket.io与Nginx的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过nginx 1.6提供静态文件,并使用socket.io代理来自Node.js Web服务器的套接字通信.

I'm trying to serve static files by nginx 1.6 and to proxy socket traffic coming from Node.js web server with socket.io .

这是nginx.conf的相关部分:

This is the relevant part of nginx.conf:

location /socket.io/ {
            proxy_pass http://localhost:3000;       
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "Upgrade";
            proxy_set_header Host $host;
        }

它可以直接在浏览器和Node.js之间完美运行,但是当与nginx 1.6代理时,socket.io花费的时间太长.握手协议需要花费很多时间,但是如果不间断,它最终会在几分钟后开始工作.

It works perfectly directly between the browser and Node.js, but socket.io takes too long when proxied with nginx 1.6. A handshaking protocol takes too much time, but if left uninterrupted it eventually starts to work after a couple of minutes.

nginx的静态文件传递效果很好.

Static files delivery by nginx works perfectly.

可能是什么问题?

更新:

我分析了一下网络流量,并确定以下请求持续了大约一分钟(这正是请求升级的时间):

I analysed a bit the network traffic and determined that the following request lasts around a minute (it's exactly when the upgrade is requested):

Sec-WebSocket-Key: LhZ1frRdl+myuwyR/T03lQ==
Cookie: io=1-A7tpvwmoGbrSvTAAA5
Connection: keep-alive, Upgrade
Upgrade: websocket
....

期望的响应是代码101 和:

Connection: upgrade
Sec-WebSocket-Accept: HXx3KKJadQYjDa11lpK5y1nENMM=
Upgrade: websocket
...

相反,浏览器会收到 400 ,并且:

instead, the browser receives 400 and:

Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:8888
Connection: keep-alive
Content-Type: application/json
Server: nginx/1.6.2
Transfer-Encoding: chunked

更新2:

我确定相同的配置可以在我的办公室计算机上正常工作,这意味着这是我的家用计算机问题.无论如何,确定到底出了什么问题会很好.

I determined that the same configuration works perfectly on my office computer, meaning that it's my home computer issue. Anyway, would be very nice to determine what exactly is going wrong.

推荐答案

在运行的服务器中,此处使用的nginx的配置为:

In a running server, the nginx's configuration being used here is:

  # Requests for socket.io are passed on to Node on port 3000
  location ~* \.io {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_set_header X-NginX-Proxy false;

      proxy_pass http://localhost:3000;
      proxy_redirect off;

      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";
    }

这篇关于Socket.io与Nginx的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆