在企业级 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
| npm uninstall socket.io socket.io-redis redis-adapter 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
| 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
| const path = require('path');
module.exports = { io: { enable: true, 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
| module.exports = appInfo => { const config = exports = {};
config.io = { init: { wsEngine: 'ws', }, cors: { origin: '*', methods: ['GET', 'POST'], credentials: true, }, 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
| module.exports = app => { const { router, controller, io } = app; io.of('/').route('chat', io.controller.chat.index); };
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)}`);
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
| <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'], 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)
客户端报错:Error: server error: Unsupported protocol version
跨域拦截:Access to XMLHttpRequest at '...' from origin '...' has been blocked by CORS policy
- 原因:Socket.IO 3.x 起默认彻底关闭跨域放行。
- 解决:在服务端
config.io.cors 中显式指定 origin 与允许的请求方式。
Egg 多进程集群下的广播失效
- 原因:Egg 默认是多 Worker 进程模型,每个客户端可能连接在不同的 Worker 甚至不同的服务器节点上。
- 解决:必须正确配置
config.io.redis。@socket.io/redis-adapter 会将广播消息推送给 Redis Pub/Sub,使所有 Worker 实例都能收到并转发给绑定的客户端。
七、相关参考链接与官方文档