微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决为什么我的 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 举报,一经查实,本站将立刻删除。