Nginx:端口 80 上的 Websocket 不起作用

Nginx:端口 80 上的 Websocket 不起作用

我正在运行一个简单的 NodeJs Websocket 应用程序,它的代码是

// Importing the required modules
const WebSocketServer = require('ws');

// Creating a new websocket server
const wss = new WebSocketServer.Server({ port: 8090 })

// Creating connection using websocket
wss.on("connection", ws => {
    console.log("new client connected");
    // sending message
    ws.on("message", data => {
        console.log(`Client has sent us: ${data}`)
    });
    // handling what to do when clients disconnects from server
    ws.on("close", () => {
        console.log("the client has connected");
    });
    // handling client connection error
    ws.onerror = function () {
        console.log("Some Error occurred")
    }
});
console.log("The WebSocket server is running on port 8090");

我想代理端口 80 的请求并将其重定向到 8090。我使用 Nginx 进行反向代理,配置如下

server {
  listen 172.30.5.139:80;
  listen 172.30.5.139:443;

  location / {
    proxy_pass "http://127.0.0.1:8090/";
    proxy_http_version  1.1;
    proxy_set_header    Upgrade $http_upgrade;
    proxy_set_header    Connection "upgrade";
    proxy_set_header    Host $http_host;
  }
}

测试时我可以通过

 ws://1.2.3.4:443/

但无法通过连接

ws://1.2.3.4/

在 Nginx 访问日志中我看到以下错误:

51.24.28.78 - - [06/Oct/2022:14:19:42 +0000] "GET /ws HTTP/1.1" 426 16 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 " "-"

需要帮助找出根本问题,因为我计划通过在 Nginx 上实施 SSL 来支持 ws 和 wss。

相关内容