Nginx + Socket.io websocket 在建立连接之前关闭问题

Nginx + Socket.io websocket 在建立连接之前关闭问题

你好,我正在运行一个 express 服务器,并且附带一个 socket.io 服务器

const { Server } = require("socket.io");
var server = http.createServer(app);

/**
 * Adding Socket io implementation
 */

const io = new Server(server, {
  cors: {
    origin: '*',
  }
});

我没有为 websocket 通信设置特定路径,因此我的 web 客户端直接使用空路径进行连接。设置SOCKET_ENDPOINT_URL为“/api”,以便它连接到我的代理后端服务器(下面的配置)(但从我看到的情况来看,它似乎完全忽略了这一点并将它/api简单地视为“/”)

import { io } from "socket.io-client";
io(env.SOCKET_ENDPOINT_URL, {
            path: ''
        })

这是我的 nginx 配置:

 location /api/ {
          proxy_http_version 1.1;
          proxy_set_header Upgrade $http_upgrade;
          proxy_set_header Connection 'upgrade';
          proxy_set_header Host $host;
          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header X-Forwarded-Proto $scheme;
          proxy_cache_bypass $http_upgrade;

          proxy_pass http://backend_server:3000/;
      }

  # Requests for socket.io are passed on to Node on port 3000
  location ~* \.io {
      proxy_pass http://backend_server:3000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "Upgrade";
    proxy_set_header Host $host;
    proxy_hide_header 'Access-Control-Allow-Origin';
    }

/api 代理运行完美,唯一的问题是 websocket 会立即在控制台上触发警告:WebSocket connection to 'ws://192.168.1.12/socket.io/?EIO=4&transport=websocket&sid=t6rV5sJp9AX35RNNAAAH' failed: WebSocket is closed before the connection is established

我尝试了多种配置,但似乎错过了一些关键的东西

答案1

我遇到了和你类似的问题。我的情况是“wss”而不是“ws”。这是我的解决方案:

客户端:

const socket = io("https://your-domain-name", {
    path: "/socket.io"
});

Nginx 反向代理:

server{
    listen 443 ssl;
    ssl_certificate  /path/to/fullchain.cer;
    ssl_certificate_key /path/to/domain.key;


    location /socket.io {
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";

        proxy_pass http://127.0.0.1:8088;

# redirect all HTTP traffic to localhost:8088;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;


    }
}

服务器端:我发现你在“初始化服务器”中遗漏了一些内容

const io = new Server(server, {
  cors: {
    origin: "*",
    methods: ["GET", "POST"],
  },
});

相关内容