node.js - 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/'});
解决方案
实际上,我已经找到了解决方案。我自己实现了房间场景,并且运行良好。为此,我刚刚实现了以下内容:
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')
})
})
推荐阅读
- xcode - Swift 4 隐藏视图并填补空白
- django - 如何在字典中保存元素倍数?
- node.js - 运行 `npm install xx`, `npm uninstall xx` 后,npm 如何知道如何更新 `package.json`
- ruby-on-rails - 将默认时间格式设为 ISO8601
- ios - 尝试读取 txt 文件时出现 TIC SSL 信任错误
- javascript - gridstack.js 根据内部内容设置 grid-stack-item 高度自动
- javascript - 如何在散点图中添加滚动条?
- java - Maven 将项目部署为 Jar - 缺少类定义
- javascript - 这个 Javascrip/节点变量/常量分配符号/语法叫什么?
- haskell - http-simple setRequestBodyLBS 背后的哲学