riku
2025-07-23 3daf8eebf8c0d5b4561f38e21c50818c8f6768b7
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
import { ws } from '@/api/index';
 
var socket;
var onMsgEvents = [];
 
const MAX_TRY_TIMES = 5;
let tryTimes = 0;
 
function startSocket() {
  if (socket) {
    socket.close();
  }
  const url = 'ws://' + ws + '/ws';
  socket = new WebSocket(url);
  // 与服务器建立连接:发送消息到服务器
  socket.onopen = () => {
    console.log('connect: ');
  };
  // 收到服务器发送的消息:event处理服务器返回的数据
  socket.onmessage = (event) => {
    // console.log('receive: ', event.data);
    onMsgEvents.forEach((e) => {
      if (typeof e === 'function') {
        e(event.data);
      }
    });
  };
  // 连接或通信过程中发生错误
  socket.onerror = (event) => {
    console.log('errror: ', event);
  };
  // 与服务器断开连接
  socket.onclose = (event) => {
    console.log('close: ', event.code);
    // setTimeout(() => {
    //   if (tryTimes < MAX_TRY_TIMES) {
    //     startSocket();
    //     tryTimes++;
    //   } else {
    //     tryTimes = 0;
    //   }
    // }, 5000);
  };
}
 
if (socket == undefined) {
  startSocket();
}
 
function send(value) {
  if (socket && socket.readyState == WebSocket.OPEN) {
    socket.send(value);
  }
}
 
function registerReceiveEvent(event) {
  if (onMsgEvents.indexOf(event) == -1) {
    onMsgEvents.push(event);
  }
}
 
function removeReceiveEvent(event) {
  const index = onMsgEvents.indexOf(event);
  if (index != -1) {
    onMsgEvents.splice(index, 1);
  }
}
 
export default { send, registerReceiveEvent, removeReceiveEvent };