升级 egg-socket.io 到 4.x

在企业级 Node.js 框架 Egg.js 的生态中,官方维护的实时通信插件 egg-socket.io 长期停留在 Socket.IO 2.1.1 版本。随着现代前端全栈技术的发展,现代客户端使用的 @socket.io/client 普遍已迈入 4.x 时代。由于 Socket.IO 在 2.x、3.x 与 4.x 之间经历了重大的协议重构(Engine.IO 协议版本升级),新版客户端直连老旧服务端时会直接触发握手异常(例如 Unsupported protocol version 或 CORS 拦截)。

既然官方插件长期未跟进维护,我们便可以在本地通过对插件源码进行“魔改”升级,将其核心升级至 Socket.IO 4.4.x 并配合全新的 @socket.io/redis-adapter 与 ioredis 实现分布式多节点集群广播。


一、为什么需要升级?(2.x 与 4.x 的核心断代差)

在动手改造前,我们需要明确升级的核心动力与破坏性变更(Breaking Changes):

维度Socket.IO 2.x (老版插件)Socket.IO 4.x (本次目标)
底层协议Engine.IO v3 协议,包体体积大Engine.IO v4 协议,握手更轻量、长轮询开销更低
CORS 跨域默认全部放行允许跨域(隐患较大)默认遵循严格同源策略,需显式声明 CORS 配置
Redis 适配器使用已被废弃的 socket.io-redis采用全新官方驱动 @socket.io/redis-adapter
Redis 客户端依赖老旧 node-redis全面拥抱现代、高性能的 ioredis(支持主从、哨兵与集群)
广播与房间 API语法偏旧,异步支持不够优雅原生支持 io.except()、广播超时确认机制等高级特性

二、依赖包版本清理与安装

首先,将老旧废弃的依赖全部清理,引入 4.x 体系下的现代化套件:

1
2
3
4
5
# 1. 卸载已废弃或存在版本冲突的老旧依赖
npm uninstall socket.io socket.io-redis redis-adapter redis

# 2. 安装 Socket.IO 4.x 及其全新的 Redis 适配器与高性能客户端
npm install socket.io@4.4.0 @socket.io/redis-adapter@7.1.0 ioredis --save

依赖选型提示:

  • 早期版本使用的 socket.io-redis 已被官方弃用并归档,迁移目标为官方统一命名空间的 @socket.io/redis-adapter。
  • @socket.io/redis-adapter@7.x 专为 socket.io@4.x 设计,在 Node.js 环境下推荐搭配 ioredis,连接管理与重试策略更为健壮。

三、插件源码魔改实战

由于没有把修改发布到 npm 私有源,我们直接将官方 egg-socket.io 拷贝至项目本地目录进行二次开发改造(推荐放在 plugins/egg-socket.io 或 lib/plugin/egg-socket.io)。

核心变动文件位于插件目录下的:lib/io.js。

1. 替换引入依赖

将废弃的 socket.io-redis 替换为新版适配器与 ioredis:

1
2
3
- const redis = require('socket.io-redis');
+ const { createAdapter } = require('@socket.io/redis-adapter');
+ const Redis = require('ioredis');

2. 重构 Redis 适配器初始化逻辑

在 lib/io.js 中找到 if (config.redis) 逻辑块。在 Socket.IO 4.x 中,Redis 适配器需要分别提供用于发布(pub)和订阅(sub)的两个独立连接,并且支持自定义配置项:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
  if (config.redis) {
- const adapter = redis(config.redis);
- // https://github.com/socketio/socket.io-redis/issues/21
- adapter.prototype.on('error', err => {
- app.coreLogger.error(err);
- });
- app.io.adapter(adapter);

+ // 1. 初始化发布者 Client 与克隆出独立的订阅者 Client
+ const pubClient = new Redis(config.redis);
+ const subClient = pubClient.duplicate();
+
+ // 2. 绑定错误监听日志,防止因为网络闪断引发未捕获异常导致 Worker 进程挂掉
+ pubClient.on('error', err => {
+ app.coreLogger.error('[egg-socket.io] pubClient error: %s', err);
+ });
+ subClient.on('error', err => {
+ app.coreLogger.error('[egg-socket.io] subClient error: %s', err);
+ });
+
+ // 3. 构建适配器配置(修复官方参数命名规范与超时机制)
+ const adapterConfig = {
+ key: config.adapter && config.adapter.key ? config.adapter.key : 'socket.io',
+ requestsTimeout: config.adapter && config.adapter.requestsTimeout ? config.adapter.requestsTimeout : 5000,
+ publishOnSpecificResponseChannel: config.adapter && config.adapter.publishOnSpecificResponseChannel ? true : false
+ };
+
+ // 4. 将 createAdapter 注入到 app.io 实例
+ app.io.adapter(createAdapter(pubClient, subClient, adapterConfig));
}

⚠️ 排坑提醒:

  • 早期代码中 publishOnSpecificResponseChannel 经常容易误拼写(如写成 requpublish...),请务必保证属性名正确。
  • subClient 务必通过 pubClient.duplicate() 派生,确保两者连接参数(密码、DB、集群等)严格一致,同时保持独立的 Redis Socket 连接以防消息阻塞。

3. 支持现代 CORS 跨域配置

Socket.IO 4.x 不再默认允许跨域,需要在服务端初始化实例化 Server 时传入 cors 选项。在 lib/io.js 的 Server 创建处补充跨域透传逻辑:

1
2
3
4
5
6
7
8
9
10
// lib/io.js 初始化 Server 实例处
const serverOptions = Object.assign({
path: config.path || '/socket.io',
cors: config.cors || {
origin: '*',
methods: ['GET', 'POST']
}
}, config.serverOptions);

const io = new Server(server, serverOptions);

四、本地插件挂载与配置

1. 配置本地插件加载(config/plugin.js)

在 Egg.js 中,通过指定 path(而非 package)将本地魔改后的插件挂载到运行环境中:

1
2
3
4
5
6
7
8
9
10
// config/plugin.js
const path = require('path');

module.exports = {
io: {
enable: true,
// 使用 path 指定本地开发插件的物理路径(推荐使用 path.join 构建跨平台路径)
path: path.join(__dirname, '../plugins/egg-socket.io'),
},
};

2. 编写项目配置(config/config.default.js)

在应用配置文件中添加对应的 io 配置,包含多节点 Redis 广播与跨域设置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// config/config.default.js
module.exports = appInfo => {
const config = exports = {};

config.io = {
init: {
wsEngine: 'ws', // 指定高效的底层引擎
},
// CORS 跨域配置(4.x 必备)
cors: {
origin: '*', // 生产环境请限制为前端域名,例如: 'https://example.com'
methods: ['GET', 'POST'],
credentials: true,
},
// 多节点分布式集群支持:Redis 配置
redis: {
host: '127.0.0.1',
port: 6379,
password: '',
db: 0,
},
// 适配器高级调优参数
adapter: {
key: 'socket.io',
requestsTimeout: 5000,
publishOnSpecificResponseChannel: false,
},
namespace: {
'/': {
connectionMiddleware: ['auth'],
packetMiddleware: ['filter'],
},
},
};

return config;
};

五、前后端联调测试

1. 服务端连接与路由(Controller / Router)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// app/router.js
module.exports = app => {
const { router, controller, io } = app;

// 监听客户端连接与自定义事件
io.of('/').route('chat', io.controller.chat.index);
};

// app/io/controller/chat.js
const Controller = require('egg').Controller;

class ChatController extends Controller {
async index() {
const { ctx, app } = this;
const message = ctx.args[0];

// 向当前发送者回复确认
await ctx.socket.emit('res', `已收到消息: ${JSON.stringify(message)}`);

// 向所有人广播(可跨 Egg Worker 与跨物理机服务器)
app.io.of('/').emit('broadcast', {
sender: ctx.socket.id,
data: message,
timestamp: Date.now(),
});
}
}

module.exports = ChatController;

2. 前端客户端连接(Socket.IO Client 4.x)

前端可直接使用标准的 socket.io-client 4.x 版本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!-- index.html -->
<script src="https://cdn.socket.io/4.4.0/socket.io.min.js"></script>
<script>
// 建立连接
const socket = io('http://127.0.0.1:7001', {
transports: ['websocket', 'polling'], // 优先 WebSocket
timeout: 5000,
});

socket.on('connect', () => {
console.log('✅ 已成功连接至 Socket.IO 4.x 服务端, ID:', socket.id);

// 发送消息
socket.emit('chat', { text: 'Hello, Egg Socket.IO 4.x!' });
});

socket.on('res', data => {
console.log('收到私信回应:', data);
});

socket.on('broadcast', data => {
console.log('收到全局广播:', data);
});

socket.on('connect_error', err => {
console.error('连接失败:', err.message);
});
</script>

六、关键踩坑与排错清单(FAQ)

  1. 客户端报错:Error: server error: Unsupported protocol version

    • 原因:前端客户端使用的是 Socket.IO 4.x,但服务端仍是 2.x,两者的 Engine.IO 协议握手格式不兼容。
    • 解决:确保服务端按照本文升级至 Socket.IO 4.x,或在未升级前严格限定客户端使用 socket.io-client@2.x。
  2. 跨域拦截:Access to XMLHttpRequest at '...' from origin '...' has been blocked by CORS policy

    • 原因:Socket.IO 3.x 起默认彻底关闭跨域放行。
    • 解决:在服务端 config.io.cors 中显式指定 origin 与允许的请求方式。
  3. Egg 多进程集群下的广播失效

    • 原因:Egg 默认是多 Worker 进程模型,每个客户端可能连接在不同的 Worker 甚至不同的服务器节点上。
    • 解决:必须正确配置 config.io.redis。@socket.io/redis-adapter 会将广播消息推送给 Redis Pub/Sub,使所有 Worker 实例都能收到并转发给绑定的客户端。

七、相关参考链接与官方文档