-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
69 lines (56 loc) · 1.83 KB
/
Copy pathserver.js
File metadata and controls
69 lines (56 loc) · 1.83 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
const WebSocket = require('ws');
const wss = new WebSocket.Server({port: 3000});
console.log('WebSocket 服务器启动在 ws://localhost:3000');
// 心跳机制
function noop() {
}
function heartbeat() {
this.isAlive = true;
}
// 每 30 秒检查一次客户端是否存活
const interval = setInterval(() => {
wss.clients.forEach((ws) => {
if (ws.isAlive === false) {
console.log('检测到不活跃客户端,终止连接');
return ws.terminate();
}
ws.isAlive = false;
ws.ping(noop); // 发送 ping
});
}, 30000); // 30秒一次心跳
wss.on('connection', (ws) => {
console.log('新客户端连接');
ws.isAlive = true;
ws.on('pong', heartbeat); // 收到 pong 就标记存活
ws.on('message', (data) => {
try {
const msg = JSON.parse(data);
console.log('收到消息:', msg);
// 处理你的各种 action
if (msg.action === 'nextTab' || msg.action === 'prevTab' ||
msg.action === 'gotoTab' || msg.action === 'gotoTabByTitle' ||
msg.action === 'refreshTab') {
// 这里广播给所有客户端(因为你的场景是 Chrome 扩展作为客户端)
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(msg));
}
});
}
} catch (e) {
console.error('消息解析失败:', e);
}
});
ws.on('close', () => {
console.log('客户端断开连接');
});
ws.on('error', (err) => {
console.error('客户端错误:', err);
});
});
// 优雅关闭
process.on('SIGINT', () => {
clearInterval(interval);
wss.close();
process.exit(0);
});