socket.io + nginx +代理问题

时间:2018-02-06 17:24:08

标签: node.js nginx socket.io

我的生产服务器上有一个运行端口8080的socket.io webservice,它响应http请求,但我认为当我的客户端通过websocket协议(ws://)

我的客户端告诉我服务器响应400(错误请求)错误,因此我的客户端或我的生产服务器出错了。我认为它是我的生产服务器,但我自己或我的同事都无法确定哪里可以确定。

这些是我们为node.js制作框提供的nginx配置。

我已将some url替换为someapp.com

NGINX

server {
        listen 80 default_server;
        listen [::]:80 default_server;
        server_name app.someapp.com;

        location / {
                proxy_set_header        X-Real-IP       $remote_addr;
                proxy_set_header        Host            $http_host;
                proxy_pass              http://127.0.0.1:3000;
        }
}

server {
        listen 8080;
        server_name app.someapp.com;
        location / {
                proxy_set_header        X-Real-IP       $remote_addr;
                proxy_set_header        Host            $http_host;
                proxy_pass              http://127.0.0.1:4000;
        }
}

server {
        listen 80;
        server_name tools.someapp.com;
        root /var/www/bbclient/dist;
        location / {
                try_files $uri $uri/ /index.html;
        }
}

它是一个非常小而简单的socket.io node.js服务器,在生产端口8080上运行

Socket.IO

const app = require('express')()
const http = require('http').Server(app)
const io = require('socket.io')(http)
const bodyParser = require('body-parser')

app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())

// this is not responding from the client
// this is working on localhost, but not in production
io.on('connection', (socket) => {
  socket.on('USER_ID', (userId) => {
    if (socket.userId) {
      socket.leave(socket.userId)
    }
    socket.userId = userId
    socket.join(userId)
  })
})

// this works over http, and responds in production
// by visiting http://app.someapp.com:8080 in the browser
app.get('/', (req, res) => {
  res.send('some app') 
})

http.listen(process.env.PORT || '8888', () => {
  console.log('listening')
})

以下是关于来自我的客户端的请求的网络选项卡的说法,导致400错误。

Chrome浏览器网络标签

enter image description here

修改1

NGINX错误日志:

2018/02/06 17:30:39 [error] 5954#5954: *86956 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 76.218.92.156, server: app.someapp.com, request: "GET /socket.io/?EIO=3&transport=polling&t=M5iAdrw&sid=Jays0pqU3StUhdjjAACb HTTP/1.1", upstream: "http://127.0.0.1:4000/socket.io/?EIO=3&transport=polling&t=M5iAdrw&sid=Jays0pqU3StUhdjjAACb", host: "someapp.com:8080", referrer: "http://tools.someapp.com/scorecards/estimating"

1 个答案:

答案 0 :(得分:1)

首先添加socket.io代理指令:

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

这是一个example。 然后尝试增加代理连接超时:

    proxy_connect_timeout 75s;
    proxy_read_timeout 75s;
    proxy_send_timeout 75s;