-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.html
56 lines (45 loc) · 1.15 KB
/
index.html
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
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Example</title>
</head>
<body>
<script>
let ws;
let reconnectInterval;
function connectWebSocket() {
ws = new WebSocket('ws://127.0.0.1:3000/ws/channel');
ws.onopen = function() {
console.log('Connected to WebSocket server');
// 发送消息到WebSocket服务器
const message = JSON.stringify({
type: 'subscribe',
channel: 'channel2'
});
ws.send(message);
};
ws.onmessage = function(event) {
console.log('Received message from WebSocket server:', event.data);
};
ws.onclose = function() {
console.log('Disconnected from WebSocket server');
// 重新连接
reconnect();
};
ws.onerror = function(error) {
console.error('WebSocket error:', error);
// 重新连接
reconnect();
};
}
function reconnect() {
clearInterval(reconnectInterval);
// 延迟重新连接
reconnectInterval = setInterval(function() {
connectWebSocket();
}, 5000);
}
connectWebSocket();
</script>
</body>
</html>