64 lines
1.2 KiB
JavaScript
64 lines
1.2 KiB
JavaScript
const WebSocket = require('ws');
|
|
const jwt = require('jsonwebtoken');
|
|
|
|
let wss = null;
|
|
|
|
const initWebSocket = (server) => {
|
|
wss = new WebSocket.Server({ server });
|
|
|
|
wss.on('connection', (ws, req) => {
|
|
// 验证管理员身份
|
|
const token = req.url.split('=')[1];
|
|
if (!token) {
|
|
ws.close();
|
|
return;
|
|
}
|
|
|
|
try {
|
|
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
|
ws.adminId = decoded.id;
|
|
ws.isAlive = true;
|
|
|
|
ws.on('pong', () => {
|
|
ws.isAlive = true;
|
|
});
|
|
|
|
ws.on('close', () => {
|
|
ws.isAlive = false;
|
|
});
|
|
} catch (error) {
|
|
ws.close();
|
|
}
|
|
});
|
|
|
|
// 心跳检测
|
|
const interval = setInterval(() => {
|
|
wss.clients.forEach((ws) => {
|
|
if (ws.isAlive === false) return ws.terminate();
|
|
ws.isAlive = false;
|
|
ws.ping();
|
|
});
|
|
}, 30000);
|
|
|
|
wss.on('close', () => {
|
|
clearInterval(interval);
|
|
});
|
|
};
|
|
|
|
const broadcastNewMessage = (message) => {
|
|
if (!wss) return;
|
|
|
|
wss.clients.forEach((client) => {
|
|
if (client.readyState === WebSocket.OPEN) {
|
|
client.send(JSON.stringify({
|
|
type: 'new_message',
|
|
data: message
|
|
}));
|
|
}
|
|
});
|
|
};
|
|
|
|
module.exports = {
|
|
initWebSocket,
|
|
broadcastNewMessage
|
|
};
|