使用 nginx 的 Socket.io [英] Socket.io with nginx

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

问题描述

我正在尝试通过 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";
    }

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

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