-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
83 lines (71 loc) · 1.93 KB
/
server.js
File metadata and controls
83 lines (71 loc) · 1.93 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
// server.js
const WebSocket = require('ws');
const PORT = 8080;
const http = require('http');
const server = http.createServer();
const wss = new WebSocket.Server({ server, path: "/ws" });
server.listen(PORT, () => {
console.log(`WebSocket 服务器启动,监听端口:${PORT}`);
});
const userState = {
me: { seconds: 0, running: false },
her: { seconds: 0, running: false }
};
// 每秒递增运行中的用户时间
setInterval(() => {
['me', 'her'].forEach(user => {
if (userState[user].running) {
userState[user].seconds++;
broadcast({
type: 'update',
user,
seconds: userState[user].seconds,
status: 'running'
});
}
});
}, 1000);
// 处理连接
wss.on('connection', function connection(ws) {
console.log('新客户端连接');
// 初次连接,把当前状态都发过去
['me', 'her'].forEach(user => {
ws.send(JSON.stringify({
type: 'update',
user,
seconds: userState[user].seconds,
status: userState[user].running ? 'running' : 'paused'
}));
});
ws.on('message', function incoming(message) {
const data = JSON.parse(message);
const user = data.user;
if (data.type === 'start') {
userState[user].running = true;
} else if (data.type === 'pause') {
userState[user].running = false;
} else if (data.type === 'reset') {
userState[user].seconds = 0;
userState[user].running = false; // 重置时也暂停计时
}
// 广播最新状态
broadcast({
type: 'update',
user,
seconds: userState[user].seconds,
status: userState[user].running ? 'running' : 'paused'
});
});
ws.on('close', () => {
console.log('客户端断开连接');
});
});
// 广播消息给所有客户端
function broadcast(data) {
const msg = JSON.stringify(data);
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(msg);
}
});
}