|
@@ -0,0 +1,95 @@
|
|
1
|
+// const WsConnecting = 0
|
|
2
|
+const WsOpen = 1
|
|
3
|
+// const WsClosing = 2
|
|
4
|
+// const WsClosed = 3
|
|
5
|
+
|
|
6
|
+export default class XWebSocket {
|
|
7
|
+ addr = ''
|
|
8
|
+ client = null
|
|
9
|
+ autoConnect = false
|
|
10
|
+ interval = undefined
|
|
11
|
+ delay = 60
|
|
12
|
+ on = { open: null, message: null, error: null, close: null }
|
|
13
|
+
|
|
14
|
+ // constructor
|
|
15
|
+ constructor ({ open, message, error, close, delay, autoConnect }) {
|
|
16
|
+ this.on = { open, message, error, close }
|
|
17
|
+
|
|
18
|
+ if (delay >= 0) {
|
|
19
|
+ this.delay = delay
|
|
20
|
+ }
|
|
21
|
+
|
|
22
|
+ this.autoConnect = autoConnect
|
|
23
|
+ }
|
|
24
|
+
|
|
25
|
+ // 连接
|
|
26
|
+ connect (addr) {
|
|
27
|
+ this.addr = addr
|
|
28
|
+ this._wsInit()
|
|
29
|
+ }
|
|
30
|
+
|
|
31
|
+ // 发送
|
|
32
|
+ send (data) {
|
|
33
|
+ if (this.client && this.client.readyState === WsOpen) {
|
|
34
|
+ this.client.send(data)
|
|
35
|
+ }
|
|
36
|
+ }
|
|
37
|
+
|
|
38
|
+ // 关闭
|
|
39
|
+ close () {
|
|
40
|
+ if (!this.client) return
|
|
41
|
+
|
|
42
|
+ this._breforeClose(false)
|
|
43
|
+
|
|
44
|
+ this.client.close()
|
|
45
|
+ this.client = null
|
|
46
|
+ }
|
|
47
|
+
|
|
48
|
+ _breforeClose (autoConnect) {
|
|
49
|
+ this._wsClearHeartbeat()
|
|
50
|
+
|
|
51
|
+ if (this.client) {
|
|
52
|
+ if (!autoConnect) {
|
|
53
|
+ // 防止 onclose 中实现 断线重连
|
|
54
|
+ this.client.onclose = undefined
|
|
55
|
+ }
|
|
56
|
+ }
|
|
57
|
+ }
|
|
58
|
+
|
|
59
|
+ _wsInit () {
|
|
60
|
+ const _self = this
|
|
61
|
+
|
|
62
|
+ this.client = new window.WebSocket(this.addr)
|
|
63
|
+ this.client.onopen = this.on.open
|
|
64
|
+ this.client.onmessage = this.on.message
|
|
65
|
+ this.client.onerror = this.on.error
|
|
66
|
+ this.client.onclose = e => {
|
|
67
|
+ if (_self.on.close) {
|
|
68
|
+ _self.on.close(e)
|
|
69
|
+ }
|
|
70
|
+
|
|
71
|
+ _self._breforeClose(_self.autoConnect)
|
|
72
|
+ _self.client = null
|
|
73
|
+
|
|
74
|
+ if (_self.autoConnect) {
|
|
75
|
+ window.setTimeout(() => _self._wsInit(), _self.delay * 1000)
|
|
76
|
+ }
|
|
77
|
+ }
|
|
78
|
+
|
|
79
|
+ this._wsHeartbeat()
|
|
80
|
+ }
|
|
81
|
+
|
|
82
|
+ _wsHeartbeat () {
|
|
83
|
+ this.interval = window.setInterval(() => {
|
|
84
|
+ if (this.client && this.client.readyState === WsOpen) {
|
|
85
|
+ this.client.send(10)
|
|
86
|
+ }
|
|
87
|
+ }, 60 * 1000)
|
|
88
|
+ }
|
|
89
|
+
|
|
90
|
+ _wsClearHeartbeat () {
|
|
91
|
+ if (this.interval !== undefined) {
|
|
92
|
+ window.clearInterval(this.interval)
|
|
93
|
+ }
|
|
94
|
+ }
|
|
95
|
+}
|