whyczyk
2021-10-09 9fc3a1d5a70a5af805b37476d47331dad0b21d65
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import getWsUrl from "@/assets/js/getWsUrl";
 
export class WebSocketClass {
    //ws地址
    constructor(url, msgCallback, time, port) {
        this.wsUrl = getWsUrl(url, port)
        this.msgCallback = msgCallback;
        this.time = time;     //心跳时间
        this.initTime = 5000   //重连时间
        this.init()
    }
    init(data) {
        let WSINWIN = 'WebSocket' in window
        if (!WSINWIN) {
            return console.log('Websocket not supported')
        }
        this.ws = new WebSocket(this.wsUrl);
        this.ws.onopen = () => {
            this.status = 'open';
            this.heartCheck();
            if (data) { this.ws.send(data) }
        };
 
        this.ws.onmessage = e => {
            if (e.data === 'pong') {
                this.pingPong = 'pong'
            } else {
                this.msgCallback(JSON.parse(e.data));
            }
        };
 
        this.ws.onclose = () => {
            clearInterval(this.pingInterval);
            clearInterval(this.pongInterval)
            if (this.status === 'close') {
                //console.log(‘手动关闭成功‘,new Date())
            } else {
                this.relink();  //非人为关闭进行重连
            }
        }
        this.ws.onerror = e => {
            console.log(e);
            this.relink()
        }
        return false
    }
 
    heartCheck() {// 心跳
        this.pingPong = 'ping';
        let timer = this.time + 1000
        this.pingInterval = setInterval(() => {
            if (this.ws.readyState === 1) {
                this.ws.send('ping')
            }
        }, this.time);
        this.pongInterval = setInterval(() => {
            if (this.pingPong === 'ping') {
                clearInterval(this.pingInterval);
                clearInterval(this.pongInterval)
                this.ws.close()
            } else {
                this.pingPong = 'ping'
            }
        }, timer)
    }
 
    sendHandle(data) {
        return this.ws.send(data);
    }
 
    relink() {
        if (this.status == 'open' && this.readyState == 1) {  //连接正常
            return
        }
        if (this.initTimeOut) { //定时器已经启动
            return;
        }
        this.initTimeOut = setTimeout(() => {
            clearInterval(this.pingInterval);
            clearInterval(this.pongInterval);
            this.initTimeOut = null;
            this.init();
        }, this.initTime)
    }
 
    // 手动关闭WebSocket
    closeMyself() {
        console.log('执行手动关闭', new Date());
        this.status = 'close';
        this.ws.close();
        this.ws = null
    }
}