You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Socket.io升级后遇问题:WebSocket频繁断开连接

WebSocket连接频繁断开排查求助

最初是因为云环境旧版Redis即将停止支持,需要升级Redis库,连带升级了一系列依赖:

  • Node.js 从16版本升级至20版本
  • NestJS 从9.2.1升级至10.3.1
  • Socket.io相关依赖更新:
    原配置:
    "@nestjs/platform-socket.io": "7.6.1",
    "@nestjs/websockets": "7.6.1",
    
    更新为:
    "@nestjs/platform-socket.io": "10.3.1",
    "@nestjs/websockets": "10.3.1",
    
  • 移除以下依赖:
    "socket.io": "2.3.0",
    "socket.io-redis": "5.2.0",
    
  • 升级客户端依赖:
    原:
    "socket.io-client": "2.3.0",
    
    升级至:
    "socket.io-client": "4.7.4",
    

现在遇到的问题是:WebSocket连接会在30秒到1分钟左右无故断开。已经排查了一天半,一开始以为是Redis的问题,后来确认是客户端到服务器的WebSocket连接问题,但始终找不到原因。已经查阅过Socket.io官方排障文档,问题仍未解决。

客户端代码

const socket = io(this.url, {
  query,
  secure: true,
  transports: ['websocket'],
  forceNew: false, // use separate sockets (helpful for debugging and potentially resilience)
  auth: { token },
  reconnection: true,
  timeout: 20_000,
  requestTimeout: 10_000,
});

服务端Redis适配器代码

import { IoAdapter } from '@nestjs/platform-socket.io';
import { ServerOptions } from 'socket.io';
import { createAdapter } from '@socket.io/redis-adapter';
import { createClient } from 'redis';
import { INestApplicationContext } from '@nestjs/common';

export class WebsocketAdapter extends IoAdapter {
  constructor(appOrHttpServer: INestApplicationContext, private redisHost: string) {
    super(appOrHttpServer);
  }

  private adapterConstructor: ReturnType<typeof createAdapter>;

  async connectToRedis(): Promise<void> {
    const pubClient = createClient({ url: `redis://${this.redisHost}:6379` });
    const subClient = pubClient.duplicate();

    pubClient.on('connect', () => {
      console.log('[pubClient] connect!');
    });
    pubClient.on('error', () => {
      console.log('[pubClient] error!');
    });
    pubClient.on('end', () => {
      console.log('[pubClient] end!');
    });
    pubClient.on('reconnecting', () => {
      console.log('[pubClient] reconnecting!');
    });
    pubClient.on('ready', () => {
      console.log('[pubClient] ready!');
    });

    subClient.on('connect', () => {
      console.log('[subClient] connect!');
    });
    subClient.on('error', () => {
      console.log('[subClient] error!');
    });
    subClient.on('end', () => {
      console.log('[subClient] end!');
    });
    subClient.on('reconnecting', () => {
      console.log('[subClient] reconnecting!');
    });
    subClient.on('ready', () => {
      console.log('[subClient] ready!');
    });

    await Promise.all([pubClient.connect(), subClient.connect()]);

    this.adapterConstructor = createAdapter(pubClient, subClient);
  }

  override createIOServer(port: number, options?: ServerOptions): any {
    const server = super.createIOServer(port, { ...options, pingTimeout: 10_000, maxHttpBufferSize: 1e6 });
    server.adapter(this.adapterConstructor);
    return server;
  }
}

这段代码和NestJS官方文档里的Redis适配器示例基本一致。

疑惑点

我对前后端的配置有些困惑,比如客户端配置里的:

timeout: 20_000,
requestTimeout: 10_000,

编辑补充

已经检查过yarn.lock里的依赖解析,确认socket.io@4.7.4和socket.io-client@4.7.4版本匹配,完整依赖列表如下:

socket.io-adapter@~2.5.2:
  version "2.5.2"
  resolved "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-2.5.2.tgz#5de9477c9182fdc171cd8c8364b9a8894ec75d12"
  integrity sha512-87C3LO/NOMc+eMcpcxUBebGjkpMDkNBS9tf7KJqcDsmL936EChtVva71Dw2q4tQcuVC+hAUy4an2NO/sYXmwRA==
  dependencies:
    ws "~8.11.0"

socket.io-client@4.7.4, socket.io-client@^4.4.1:
  version "4.7.4"
  resolved "https://registry.npmjs.org/socket.io-client/-/socket.io-client-4.7.4.tgz#5f0e060ff34ac0a4b4c5abaaa88e0d1d928c64c8"
  integrity sha512-wh+OkeF0rAVCrABWQBaEjLfb7DVPotMbu0cgWgyR0v6eA4EoVnAwcIeIbcdTE3GT/H3kbdLl7OoH2+asoDRIIg==
  dependencies:
    "@socket.io/component-emitter" "~3.1.0"
    debug "~4.3.2"
    engine.io-client "~6.5.2"
    socket.io-parser "~4.2.4"

socket.io-parser@~4.2.4:
  version "4.2.4"
  resolved "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.4.tgz#c806966cf7270601e47469ddeec30fbdfda44c83"
  integrity sha512-/GbIKmo8ioc+NIWIhwdecY0ge+qVBSMdgxGygevmdHj24bsfgtCmcUUcQ5ZzcylGFHsN3k4HB4Cgkl96KVnuew==
  dependencies:
    "@socket.io/component-emitter" "~3.1.0"
    debug "~4.3.1"

socket.io@4.7.4, socket.io@^4.4.1:
  version "4.7.4"
  resolved "https://registry.npmjs.org/socket.io/-/socket.io-4.7.4.tgz#2401a2d7101e4bdc64da80b140d5d8b6a8c7738b"
  integrity sha512-DcotgfP1Zg9iP/dH9zvAQcWrE0TtbMVwXmlV4T4mqsvY+gw+LqUGPfx2AoVyRk0FLME+GQhufDMyacFmw7ksqw==
  dependencies:
    accepts "~1.3.4"
    base64id "~2.0.0"
    cors "~2.8.5"
    debug "~4.3.2"
    engine.io "~6.5.2"
    socket.io-adapter "~2.5.2"
    socket.io-parser "~4.2.4"

有没有人能指出配置里的问题?这次升级过程太折腾了,感谢任何帮助!需要更多代码的话我可以补充,谢谢!

内容的提问来源于stack exchange,提问作者maxime1992

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 08:00:54