简体   繁体   English

将 socket.io 升级到 v3 后出现快速会话问题

[英]Issue with express-session after upgrading socket.io to v3

I'm working on a Node/Express backend that uses the socket.io library to send events to the frontend.我正在使用socket.io库将事件发送到前端的 Node/Express 后端。 We've decided to upgrade it (both in the backend and frontend) to version 3 and we're having an issue that we can't solve so far.我们决定将它(在后端和前端)升级到版本 3,但我们遇到了一个目前无法解决的问题。 I'll try to explain it:我会试着解释一下:

  • Whenever a client authenticates with the backend, it opens a socket connection between them每当客户端向后端进行身份验证时,它都会在它们之间打开一个套接字连接
  • We use the express-session library to save the new socket ID into the session with the following code:我们使用express-session库将新的套接字 ID 保存到 session 中,代码如下:
this._socketIO.on('connection', socket => {
    // Add the socket id to the session
    socket.request.session.socketId = socket.id;
    socket.request.session.save();

    logger().info(`WebSocket: User connected (ID: ${socket.id})`);
    
    socket.on('disconnect', () => {
        logger().info(`WebSocket: User disconnected (ID: ${socket.id})`);
    });
});
  • After updating the socket library to v3.0.4, the session doesn't have the socketId field anymore.将套接字库更新到 v3.0.4 后,session 不再具有socketId字段。
  • I've realized that if I restart the backend server, while there's a logged client in the UI (and, so, there's an existing session file), it works fine.我已经意识到,如果我重新启动后端服务器,而 UI 中有一个已记录的客户端(因此,存在一个现有的 session 文件),它工作正常。 If I log out from the UI and log in again (so it creates a new session file), it doesn't work again.如果我从 UI 注销并再次登录(因此它会创建一个新的 session 文件),它就无法再次工作。

I've been checking the migration documentation from the official page ( https://socket.io/docs/v3/migrating-from-2-x-to-3-0 ) but I couldn't find an answer for this problem.我一直在从官方页面( https://socket.io/docs/v3/migrating-from-2-x-to-3-0 )检查迁移文档,但我找不到这个问题的答案.

Any clues?有什么线索吗? Thanks in advance,提前致谢,

We've found out that the problem is because we've registered 2 session middlewares, one for the regular requests and another one for the socket requests (to save the associated socket ID) and sometimes it fails due to a race condition.我们发现问题是因为我们注册了 2 个 session 中间件,一个用于常规请求,另一个用于套接字请求(以保存关联的套接字 ID),有时由于竞争条件而失败。 Depending on which requests is managed first, the session is saved with the socket id or not.根据首先管理的请求,session 是否与套接字 id 一起保存。

We've delayed the socket connection after all the needed login requests are done and now it's working fine.在完成所有需要的登录请求后,我们已经延迟了套接字连接,现在它工作正常。

Cheers,干杯,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM