whyczyk
2022-05-05 5a087f3a8f6db1f6344dc4a79af2e4c85d27cf1b
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
import getWsUrl from './getWsUrl';
 
export default function (url) {
  const wsUri = getWsUrl(url);
  // 重连时间间隔 默认10秒
  const reConnectDelay = 10 * 1000;
  return {
    data() {
      return {
        SOCKET: null,
        reConnectDelay,
        timer: null
      }
    },
    computed: {
      isWSOpen () {
        return !!(this.SOCKET && 1 == this.SOCKET.readyState);
      }
    },
    methods: {
      // 打开链接
      openSocket() {
        // 初始化WebSocket
        this.WSClose();
        this.WSInit();
      },
      // 初始化
      WSInit() {
        // 未被初始化初始化
        if (!this.isWSOpen) {
          console.log('=====WSinit, url:', wsUri);
          this.SOCKET = new WebSocket(wsUri);
          this.SOCKET.onmessage = this.onWSMessage;
          this.SOCKET.onopen = this.onWSOpen;
          this.SOCKET.onerror = this.onWSError;
          this.SOCKET.onclose = this.WSClose;
        }
      },
      onWSOpen() {
      },
      onWSMessage() {
      },
      onWSError(Event) {
        console.log('链接失败', wsUri);
        this.WSClose(Event);
      },
      WSClose(Event) {
        if (this.isWSOpen) {
          console.log('链接关闭', wsUri, Event);
          this.SOCKET.close();
          this.SOCKET = null;
          // 没有event对象 则为手动关闭
          if (Event) {
            this.reConnect();
          }
        }
      },
      // 重连
      reConnect () {
        // 重连计时开始 就不另重连
        if (this.timer) {
          return;
        }
        this.timer = setTimeout(() => {
          this.timer = null;
          this.WSInit();
        }, this.reConnectDelay);
      }
    },
    mounted () {
      this.openSocket();
    },
    beforeDestroy() {
      this.WSClose();
    }
  }
}