-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebsocket.js
More file actions
168 lines (138 loc) · 4.34 KB
/
websocket.js
File metadata and controls
168 lines (138 loc) · 4.34 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
const WebSocket = require('ws')
let wss = null
const pingInterval = parseInt(process.env.WS_PING_INTERVAL || '30000')
const maxClients = parseInt(process.env.WS_MAX_CLIENTS || '100')
// 初始化WebSocket服务器
function initWebSocket(server) {
wss = new WebSocket.Server({
server,
maxClients: maxClients
})
wss.on('connection', (ws) => {
console.log('📡 WebSocket客户端已连接')
// 设置客户端标识
ws.clientId = Date.now() + Math.random().toString(36).substr(2, 5)
ws.isAlive = true
// 心跳检测
ws.on('pong', () => {
ws.isAlive = true
})
ws.on('message', (message) => {
try {
const data = JSON.parse(message)
console.log(`📨 收到来自客户端 ${ws.clientId} 的消息:`, data)
// 处理客户端消息
if (data.type === 'subscribe') {
ws.subscribed = true
ws.channels = data.channels || ['reports']
// 发送确认消息
ws.send(JSON.stringify({
type: 'subscribed',
channels: ws.channels,
message: `已订阅频道: ${ws.channels.join(', ')}`
}))
console.log(`✅ 客户端 ${ws.clientId} 已订阅频道: ${ws.channels.join(', ')}`)
}
} catch (error) {
console.error('❌ 解析WebSocket消息失败:', error)
}
})
ws.on('close', () => {
console.log(`📡 WebSocket客户端 ${ws.clientId} 已断开`)
})
ws.on('error', (error) => {
console.error(`❌ WebSocket客户端 ${ws.clientId} 错误:`, error)
})
// 发送初始连接消息
ws.send(JSON.stringify({
type: 'connected',
clientId: ws.clientId,
message: '已连接到实时通报系统',
time: new Date().toISOString()
}))
})
// 定期检查WebSocket连接
const pingIntervalId = setInterval(() => {
wss.clients.forEach((ws) => {
if (ws.isAlive === false) {
console.log(`🔌 关闭无响应的客户端 ${ws.clientId}`)
return ws.terminate()
}
ws.isAlive = false
ws.ping()
})
}, pingInterval)
// 服务器关闭时清理
wss.on('close', () => {
clearInterval(pingIntervalId)
})
console.log('📡 WebSocket服务器已初始化')
return wss
}
// 向所有订阅的客户端广播消息
function broadcastReport(report, channel = 'reports') {
if (!wss) {
console.warn('⚠️ WebSocket服务器未初始化,无法广播消息')
return 0
}
console.log(`📢 广播 ${channel} 消息到所有客户端:`, report)
// 确保消息格式统一
const standardizedReport = {
id: report.id,
class: Number(report.class),
headteacher: report.headteacher || `班主任${report.class}`,
isadd: Boolean(report.isadd),
changescore: Number(report.changescore),
note: String(report.note || ''),
submitter: String(report.submitter || '系统'),
submittime: report.submittime || new Date().toISOString(),
reducetype: report.reducetype || null
}
const message = JSON.stringify({
type: 'new-report',
channel,
data: standardizedReport,
time: new Date().toISOString()
})
let sentCount = 0
wss.clients.forEach((client) => {
if (
client.readyState === WebSocket.OPEN &&
client.subscribed &&
(!client.channels || client.channels.includes(channel))
) {
try {
client.send(message)
sentCount++
console.log(`✅ 消息已发送到客户端 ${client.clientId}`)
} catch (error) {
console.error(`❌ 发送消息到客户端 ${client.clientId} 失败:`, error)
}
}
})
console.log(`✅ 消息已发送给 ${sentCount} 个客户端`)
return sentCount
}
// 向特定客户端发送消息
function sendToClient(clientId, message) {
if (!wss) return false
let sent = false
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN && client.clientId === clientId) {
client.send(JSON.stringify(message))
sent = true
}
})
return sent
}
// 获取连接的客户端数量
function getConnectedClientsCount() {
if (!wss) return 0
return [...wss.clients].filter(client => client.readyState === WebSocket.OPEN).length
}
module.exports = {
initWebSocket,
broadcastReport,
sendToClient,
getConnectedClientsCount
}