-
Notifications
You must be signed in to change notification settings - Fork 284
Expand file tree
/
Copy pathwebsocket.js
More file actions
243 lines (211 loc) · 7.5 KB
/
websocket.js
File metadata and controls
243 lines (211 loc) · 7.5 KB
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
/**
* WebSocket控制器模块
* 提供WebSocket连接管理、实时日志广播和客户端通信功能
* @module websocket-controller
*/
import {validateBasicAuth} from "../utils/api_validate.js";
import {toBeijingTime} from "../utils/datetime-format.js";
// WebSocket 客户端管理
const wsClients = new Set();
// 需要拦截的console方法列表
const CONSOLE_METHODS = [
'log', 'error', 'warn', 'info', 'debug',
'time', 'timeEnd', 'timeLog',
'assert', 'clear', 'count', 'countReset',
'dir', 'dirxml', 'group', 'groupCollapsed', 'groupEnd',
'table', 'trace', 'profile', 'profileEnd'
];
// 原始 console 方法备份
const originalConsole = {};
// 动态备份所有console方法
CONSOLE_METHODS.forEach(method => {
if (typeof console[method] === 'function') {
originalConsole[method] = console[method];
}
});
// 广播消息到所有 WebSocket 客户端
function broadcastToClients(message) {
const deadClients = [];
wsClients.forEach(client => {
try {
// 使用WebSocket的OPEN常量进行状态检查
if (client.readyState === client.OPEN) {
client.send(message);
} else {
deadClients.push(client);
}
} catch (error) {
originalConsole.error('Error broadcasting to client:', error);
deadClients.push(client);
}
});
// 清理断开的连接
deadClients.forEach(client => wsClients.delete(client));
}
// Console 拦截器
function interceptConsole() {
const createInterceptor = (level, originalMethod) => {
return function (...args) {
// 调用原始方法
originalMethod.apply(console, args);
// 广播到所有 WebSocket 客户端
if (wsClients.size > 0) {
const message = {
type: 'console',
level: level,
timestamp: toBeijingTime(new Date()),
content: args.map(arg =>
typeof arg === 'object' ? JSON.stringify(arg, null, 2) : String(arg)
).join(' ')
};
broadcastToClients(JSON.stringify(message));
}
};
};
// 动态拦截所有console方法
CONSOLE_METHODS.forEach(method => {
if (originalConsole[method]) {
console[method] = createInterceptor(method, originalConsole[method]);
}
});
}
// 恢复原始 console
function restoreConsole() {
// 动态恢复所有console方法
CONSOLE_METHODS.forEach(method => {
if (originalConsole[method]) {
console[method] = originalConsole[method];
}
});
}
// 启动 console 拦截
interceptConsole();
/**
* WebSocket控制器插件
* @param {Object} fastify - Fastify实例
* @param {Object} options - 插件选项
* @param {Function} done - 完成回调
*/
export default (fastify, options, done) => {
/**
* WebSocket连接路由
* GET /ws - 建立WebSocket连接
*/
fastify.get('/ws', {websocket: true}, (socket, req) => {
const clientId = Date.now() + Math.random();
originalConsole.log(`WebSocket client connected: ${clientId}`);
originalConsole.log('Socket type:', typeof socket);
originalConsole.log('Socket has send method:', typeof socket.send);
// 添加到客户端集合
wsClients.add(socket);
// 设置连接属性
socket.clientId = clientId;
socket.isAlive = true;
socket.lastPing = Date.now();
// 发送欢迎消息 - 先检查send方法是否存在
if (typeof socket.send === 'function') {
socket.send(JSON.stringify({
type: 'welcome',
message: 'WebSocket connection established',
clientId: clientId,
timestamp: Date.now()
}));
} else {
originalConsole.error('Socket does not have send method');
}
// 设置心跳检测
const heartbeatInterval = setInterval(() => {
if (!socket.isAlive) {
originalConsole.log(`Client ${clientId} failed heartbeat, terminating`);
clearInterval(heartbeatInterval);
wsClients.delete(socket); // 修复内存泄露:从客户端集合中移除
socket.terminate();
return;
}
socket.isAlive = false;
socket.ping();
}, 30000); // 30秒心跳检测
// 处理pong响应
socket.on('pong', () => {
socket.isAlive = true;
});
// 处理消息
socket.on('message', (message) => {
try {
const data = JSON.parse(message.toString());
if (data && data.type === 'heartbeat') {
originalConsole.debug(`Received from ${clientId}:`, data);
} else {
originalConsole.log(`Received from ${clientId}:`, data);
}
// 回显消息
if (socket.readyState === socket.OPEN) {
socket.send(JSON.stringify({
type: 'echo',
originalMessage: data,
timestamp: Date.now(),
clientId: clientId
}));
}
} catch (error) {
originalConsole.error('Error processing message:', error);
if (socket.readyState === socket.OPEN) {
socket.send(JSON.stringify({
type: 'error',
message: 'Invalid JSON format',
timestamp: Date.now()
}));
}
}
});
// 处理连接关闭
socket.on('close', (code, reason) => {
originalConsole.log(`Client ${clientId} disconnected: ${code} ${reason}`);
wsClients.delete(socket);
clearInterval(heartbeatInterval);
});
// 处理错误
socket.on('error', (error) => {
originalConsole.error(`WebSocket error for client ${clientId}:`, error);
wsClients.delete(socket);
clearInterval(heartbeatInterval);
});
});
/**
* WebSocket状态查询接口
* GET /ws/status - 获取WebSocket服务状态
*/
fastify.get('/ws/status', {preHandler: validateBasicAuth}, async (request, reply) => {
return {
status: 'ok',
timestamp: toBeijingTime(new Date()),
clients: wsClients.size,
console_intercepted: true
};
});
/**
* 手动广播接口
* POST /ws/broadcast - 向所有WebSocket客户端广播消息
*/
fastify.post('/ws/broadcast', {preHandler: validateBasicAuth}, async (request, reply) => {
const {message} = request.body;
if (!message) {
return reply.code(400).send({error: 'Message is required'});
}
const broadcastMessage = {
type: 'broadcast',
timestamp: toBeijingTime(new Date()),
content: message
};
broadcastToClients(JSON.stringify(broadcastMessage));
return {
status: 'ok',
timestamp: toBeijingTime(new Date()),
message: 'Message broadcasted',
clients: wsClients.size
};
});
done();
};
// 导出工具函数供其他模块使用
export {wsClients, broadcastToClients, originalConsole, interceptConsole, restoreConsole};