与react和express(nginx,docker)建立网络套接字通信

2023-12-23

尝试设置 websocket 连接,当我在本地主机环境中时它工作正常,但是一旦我设置了 docker 环境,客户端(react)就很难与 Express 建立 web-socket 通信。我应该定义什么网址才能在两者之间打开网络套接字?我试过了http:/api or http://localhost:3050但他们都没有成功

这是我的 nginx.conf 文件

upstream client {
    server client:3000;
}

upstream api {
    server api:8080;
}

server{

    listen 80;

    location / {
        proxy_pass http://client;
    }

    location /socket.io {
        proxy_pass http://api;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
    }

    location /api{
        rewrite /api/(.*) /$1 break;
        proxy_pass http://api;
    }
}

这是我的码头工人写的

version: "3"
services:
  nginx:
    restart: always
    image: coco/nginx
    build:
      dockerfile: Dockerfile.dev
      context: ./nginx
    ports:
      - "3050:80"
  api:
    image: coco/server
    build:
      dockerfile: Dockerfile.dev
      context: ./server
    volumes:
      - /app/node_modules
      - ./server:/app
  client:
    image: coco/client
    build:
      dockerfile: Dockerfile.dev
      context: ./client
    volumes:
      - /app/node_modules
      - ./client:/app

关键问题是在 React 容器中,它需要使用这行代码 const socket = socketIOClient("http:/api"); 设置 websocket 本身,当它在 localhost 上时工作正常,现在当我启动 docker-compose 时, 它失败。但是服务器能够接收 axios 调用等,只是无法从客户端建立网络套接字

在我的 app.js 文件中我有这个

// configuring the port which is from config folder
let server = app.listen(config.port, function (err) {
    if (err) throw err;
    console.log("Server started on port " + config.port);
});

const io = require('socket.io').listen(server)
require('./routes/routes')(app, io)

在我的反应组件中,我有一个按钮,按下时它会执行以下逻辑

  const socket = socketIOClient("http://api");
    socket.on("connect", () => {
      console.log("Socket Connected");
      socket.on("tweets", data => {
       console.log(data)
      });
    });

但它不显示任何东西,也不连接到任何东西

UPDATE:

有一次它工作时没有做太多改变,然后它冻结了,我添加了几行代码试图调试它

 socket.on("error", function(err) {
        console.log("Socket.IO Error");
        console.log(err); // this is changed from your code in last comment
      });

这就是我发现的

Socket.IO Error
 Invalid namespace

如果有人再次遇到这个问题,这里是解决方案

1)在socket.io实例中指定生产路径

const socket = socketIOClient({ path: "/socket.io" });

2)nginx内部,需要配置路由

location /socket.io {
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_http_version 1.1;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $host;
    proxy_pass http://api/socket.io/;
}

注意:位置与上一步中 socketIOClient 中指定的路径相同。然后, proxy_pass: 通过 /socket.io 引用服务器本身

希望它可以帮助某人

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

与react和express(nginx,docker)建立网络套接字通信 的相关文章

随机推荐