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
| import express from 'express';
import { createServer } from 'http';
import { WebSocket, WebSocketServer } from 'ws';
import { fileURLToPath } from 'url';
import { join, dirname } from 'path';
// 获取 __dirname
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// 创建 Express 应用和 HTTP 服务器
const app = express();
const server = createServer(app);
// 设置 WebSocket 服务器
const wss = new WebSocketServer({ server });
wss.on('connection', (ws) => {
// 设定心跳检测时间间隔
const interval = setInterval(() => {
if (ws.readyState === WebSocket.OPEN) {
ws.ping(); // 发送 ping 消息,检测客户端是否存活
}
}, 30000); // 每30秒发送一次心跳检测
ws.on('pong', () => {
console.log('received pong from client');
});
ws.on('message', (message) => {
console.log('ws message')
const data = JSON.parse(message);
});
ws.on('close', () => {
clearInterval(interval); // 当连接关闭时清理定时器
console.log('ws close');
});
});
// 配置 Express 处理静态文件
app.use(express.static(join(__dirname, '../public/dist')));
// 启动服务器
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server is listening on http://localhost:${PORT}`);
});
|