首页 > 解决方案 > socket.io 使在 nginx 反向代理上运行的任何 socket.emit 失败

问题描述

我有一个在 dockerized 环境中运行的节点应用程序就好了。它通过 HTTP 和本地运行一切正常。只有当我使用 Nginx 反向代理时,socket.emit 才不会返回任何内容。

我的 Nginx 配置:

   location /verification/ {
      proxy_pass http://127.0.0.1:3005/;
      proxy_set_header X-Forwarded-Host $server_name;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-Proto $scheme;
      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;
   }

我的套接字连接(客户端):

const socket = io( 
   'https://mywebsite.com',
   { path:  + '/verification/socket.io/', 
     secure: true, 
     rejectUnauthorized: false 
   }, fn)

我的服务器配置:

const io = socket(http, {path: '/socket.io/'});

标签: node.jsdockersocketsnginxreverse-proxy

解决方案


实际上,我已经找到了解决方案。我自己实现了房间场景,并且运行良好。为此,我刚刚实现了以下内容:

const clients = {};
io.to('/verification/').connection(function(){
   
  clients[socket.id] = {room: null, id: socket.id};
  socket.on('message', function(payload){
      if(payload.intent === 'join'){
         clients[socket.id] = {...clients[socket.id], room: payload.room};
      }
  });

  //and to broadcast messages:

   
   Object.values(clients)
       .map(client => {
          socket.to(client.id).emit('message', 'foo message')
       })
})


推荐阅读