为什么我的 Socket.io 客户端无法使用 NGINX 反向代理连接到 AWS EC2 节点应用程序

问题描述

我开发了一个使用 socket.io 的实时应用程序,它可以在开发环境中运行,但是一旦我将其部署到生产环境中,它就会停止运行。

我的生产 Node.js 应用部署在 AWS EC2 上,Nginx 用于反向代理。

对于服务器上的 socket.io,我创建了另一个监听 6444 端口的服务器,

这是我的服务器端代码

const app = require("express")();
const http = require("http");
const server = http.createServer(app);
const Server = require("socket.io");
const io = new Server(server);
const firebase = require("firebase/app");
const firebaseConfig = require("./firebaseConfig");
const firebaseApp = firebase.initializeApp(firebaseConfig);
const firebaseDB = require("firebase/database");
let hostname = "";

function RasBerryPiSocket() {
  io.on("connection",function (socket) {
    socket.on("Server",(data) => {
      hostname = data.device_id;
      firebase
        .database()
        .ref(`wifi/${data.device_id}`)
        .update({ Status: data.status })
        .catch((error) => console.log(error));
    });

    socket.on("disconnect",function (device_id) {
      firebase
        .database()
        .ref(`wifi/${hostname}`)
        .update({ Status: "offline" })
        .catch((error) => console.log(error));
    });
  });

  app.get("/",(req,res) => res.send("Hello"));

  server.listen(6444,function () {
    console.log("listening on *6444");
  });
}



module.exports = RasBerryPiSocket;

这是我的客户端代码

const io = require("socket.io-client");
const socket = io.connect("https://<IP of EC2 instance>"); 

function RealTimeSocket(hostname) {
  socket.on("connect",() => {
    //console.log(socket,"Starting Socket Connection");
    console.log(socket.id); // false
  });

  socket.on("CHI",(data) => {
    console.log(data,hostname);
  });

  setInterval(
    () =>
      socket.emit("Server",{
        device_id: hostname,socket_id: socket.id,status: "online",}),1000
  );
}

module.exports = RealTimeSocket;

这是我的 Nginx 配置:

 location / {
                # First attempt to serve request as file,then
                # as directory,then fall back to displaying a 404.
                #try_files $uri $uri/ =404;
        proxy_pass http://localhost:4000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        }
location /chat/ {
      proxy_pass http://localhost:6444;
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection 'upgrade';
      proxy_set_header Host $host;
      proxy_cache_bypass $http_upgrade;
     }

我可以在端口 4000 上访问我的所有 API,而 socket.io 端口 6444 让我超时。

请帮助我已经 4 天了,我正在寻找解决方案,但没有任何效果

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)