wangzhibo
2026-07-18 708f980f0f351bfe47d7936151bf52ed4d4a7bc4
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
---
description: 即时通讯(Socket)
globs: 
---
# 即时通讯(Socket)
 
`cool-admin`即时通讯功能基于[Socket.io(v4)](https://socket.io/docs/v4)开发,[midwayjs 官方 Socket.io 文档](http://midwayjs.org/docs/extensions/socketio)
 
## 配置
 
`configuration.ts`
 
```ts
import * as socketio from "@midwayjs/socketio";
 
@Configuration({
  imports: [
    // socketio http://www.midwayjs.org/docs/extensions/socketio
    socketio,
  ],
  importConfigs: [join(__dirname, "./config")],
})
export class ContainerLifeCycle {
  @App()
  app: koa.Application;
 
  async onReady() {}
}
```
 
## 配置`config/config.default.ts`
 
需要配置 redis 适配器,让进程之间能够进行通讯
 
```ts
import { CoolConfig, MODETYPE } from "@cool-midway/core";
import { MidwayConfig } from "@midwayjs/core";
import * as fsStore from "@cool-midway/cache-manager-fs-hash";
import { createAdapter } from "@socket.io/redis-adapter";
// @ts-ignore
import Redis from "ioredis";
 
const redis = {
  host: "127.0.0.1",
  port: 6379,
  password: "",
  db: 0,
};
 
const pubClient = new Redis(redis);
const subClient = pubClient.duplicate();
 
export default {
  // ...
  // socketio
  socketIO: {
    upgrades: ["websocket"], // 可升级的协议
    adapter: createAdapter(pubClient, subClient),
  },
} as MidwayConfig;
```
 
## 服务端
 
```ts
import {
  WSController,
  OnWSConnection,
  Inject,
  OnWSMessage,
} from "@midwayjs/core";
import { Context } from "@midwayjs/socketio";
/**
 * 测试
 */
@WSController("/")
export class HelloController {
  @Inject()
  ctx: Context;
 
  // 客户端连接
  @OnWSConnection()
  async onConnectionMethod() {
    console.log("on client connect", this.ctx.id);
    console.log("参数", this.ctx.handshake.query);
    this.ctx.emit("data", "连接成功");
  }
 
  // 消息事件
  @OnWSMessage("myEvent")
  async gotMessage(data) {
    console.log("on data got", this.ctx.id, data);
  }
}
```
 
## 客户端
 
```ts
const io = require("socket.io-client");
 
const socket = io("http://127.0.0.1:8001", {
  auth: {
    token: "xxx",
  },
});
 
socket.on("data", (msg) => {
  console.log("服务端消息", msg);
});
```
 
## 注意事项
 
如果部署为多线程的,为了让进程之间能够进行通讯,需要配置 redis 适配器,[配置方式](http://midwayjs.org/docs/extensions/socketio#%E9%85%8D%E7%BD%AE-redis-%E9%80%82%E9%85%8D%E5%99%A8)
 
```ts
// src/config/config.default
import { createRedisAdapter } from "@midwayjs/socketio";
 
export default {
  // ...
  socketIO: {
    adapter: createRedisAdapter({ host: "127.0.0.1", port: 6379 }),
  },
};
```