首页 > 解决方案 > Socket.io 客户端不断在 Heroku 上重新连接,与 node.js 反应

问题描述

我已经在 Heroku 上部署了我的 Web 应用程序,虽然一切正常,但 websockets 不断断开连接并重新连接到服务器,导致套接字之间的消息传递中断(例如,如果一个套接字在房间里并重新连接,它们不再在那个房间)。

我发现许多问题与我的问题相似,通常是端口设置不正确的问题。此外,在 localhost 中,websocket 不会重新连接,一切正常。

这是我的服务器代码:

// .../express/app.js
const app = express();
// routes and app config
module.exports = app;

...
// index.js 
const app = require('./express/app');
const cors = require('cors');
const sequelize = require('./sequelize');
const PORT = process.env.PORT || 5000;

const httpServer = require('http').createServer(app);
const io = require('socket.io')(httpServer, {
    cors: {
        origin: "*"
    },
    transports: ['websocket']
});
...
httpServer.listen(PORT, () => {
    console.log(`Express server started on port ${PORT}.`);
});

和客户端代码:

var socket = io({transports: ['websocket'], upgrade: false})
// I have also tried with reconnection: false but it is not what I want as it handles just one event 
// and then disconnects. I want the socket to stay connected until the user logs out (or closes the 
// browser

Heroku 上的日志:

2021-01-25T19:14:44.748545+00:00 heroku[router]: at=info method=GET path="/socket.io/EIO=4&transport=websocket" host=ad-hunter.herokuapp.com request_id=b91ec827-5706-49b0-b94f-0e2938850110 fwd="82.23.237.64" dyno=web.1 connect=0ms service=110087ms status=101 bytes=129 protocol=https
2021-01-25T19:14:46.365100+00:00 heroku[router]: at=info method=GET path="/socket.io/?EIO=4&transport=websocket" host=ad-hunter.herokuapp.com request_id=78876cd4-7159-4bb1-abe5-f3ca65e9369e fwd="82.23.237.64" dyno=web.1 connect=0ms service=110082ms status=101 bytes=129 protocol=https
2021-01-25T19:15:12.941661+00:00 heroku[router]: at=info method=GET path="/socket.io/?EIO=4&transport=websocket" host=ad-hunter.herokuapp.com request_id=e2cbc234-695b-4403-95ad-1dcb8b5b520e fwd="82.23.237.64" dyno=web.1 connect=0ms service=60006ms status=101 bytes=129 protocol=https
2021-01-25T19:15:16.705544+00:00 heroku[router]: at=info method=GET path="/socket.io/?EIO=4&transport=websocket" host=ad-hunter.herokuapp.com request_id=edf6c087-bb19-4f83-afea-6099e6dc1132 fwd="82.23.237.64" dyno=web.1 connect=0ms service=135127ms status=101 bytes=129 protocol=https
2021-01-25T19:15:35.975365+00:00 heroku[router]: at=info method=GET path="/socket.io/?EIO=4&transport=websocket" host=ad-hunter.herokuapp.com request_id=d22930dd-1b05-454d-86e8-447a95d1ae56 fwd="82.24.37.118" dyno=web.1 connect=0ms service=85068ms status=101 bytes=129 protocol=https

网络请求:
网络请求

在 chrome 的控制台中(不断重复):
控制台日志

到目前为止,这些是我的想法:我知道服务器套接字 ping 客户端套接字以查看它们是否仍然处于活动状态,但是为什么它们在 Heroku 而不是 localhost 上重新连接?Heroku 是否以某种方式刷新服务器或客户端?
我想要的是每个客户端会话只有一个一致的套接字(每次用户登录时套接字连接到服务器)。

注意:玩游戏功能仅适用于相应的 chrome 扩展(这是我最后一年的项目,它是非常实验性的)。

标签: node.jsreactjsherokusocket.io

解决方案


好吧,我终于不小心发现了这个问题。据我所知,我的互联网运行良好,我没有理由认为重新连接是由于我的互联网丢失和重新连接。

但是,我尝试下载一首歌曲,但每次下载都会失败(网络错误),这意味着我的互联网有问题。我设置了一个移动热点,现在一切正常。这也解释了为什么在 localhost 中一切正常。


推荐阅读