-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathReconnetWebsocket.js
224 lines (198 loc) · 5.95 KB
/
ReconnetWebsocket.js
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
/**
* @description 基于sockjs+stompjs的websocket自动重连工具类
* 封装内容:
* 1. 一个类对象只使用一个sessionId,断开重连后也是使用这一个sessionId进行重连
* 2. 对连接状态做封装,防止重复调用connect导致重复连接
* 3. 断线重连机制
* 4. stomp内执行websocket的onclose回调时不会把错误信息带给回调,这里做了封装,会把原生websocket错误对象以参数形式传给回调
* 5. 当sockjs处于连接中状态时,disconnect处理
* 6. 断网过程中不重连,网络恢复后再自动重连
* @author zhoujie
*/
import SockJs from '@aicc/assets/sockjs'
import { generateRandom } from '@aicc/utils'
import Stomp from 'stompjs'
const logger = require('@aicc/utils/logger').logger('ReconnetWebsocket')
const reChorme = new RegExp('Chrome/(\\d+\\.\\d+(?:\\.\\d+\\.\\d+))?')
const isChrome = () => reChorme.test(window.navigator.userAgent)
// 连接状态
const CONNECTING = 'connecting'
const CONNECTED = 'connected'
const FAILD = 'failed'
const DISCONNECTING = 'disconnecting'
const DISCONNECTED = 'disconnected'
export default class ReconnetWebsocket {
constructor(url) {
this.status = DISCONNECTED
this.url = url
this.stompClient = undefined
this.timeout = null
this.sessionId = generateRandom()
this.successCb = () => {}
this.errorCb = () => {}
this.params = {}
this.shouldReconnect = true
}
_onConnectEnd(fn) {
this.connectEndFns = this.connectEndFns || []
this.connectEndFns.push(fn.bind(this))
}
_connectEnded() {
if (this.connectEndFns) {
this.connectEndFns.forEach(fn => fn())
this.connectEndFns = []
}
}
connect(params = {}, successCb = () => {}, errorCb = () => {}) {
/**
* 用户主动调用connect
*
* 这种情况需要重连以维护ws的稳定性
*/
this.shouldReconnect = true
return new Promise(resolve => {
if (params instanceof Function) {
errorCb = successCb
successCb = params
params = {}
}
this.params = params
this.errorCb = errorCb
this.successCb = successCb
if (this.status === CONNECTED) {
successCb()
resolve()
return
}
if (this.status === CONNECTING) {
return
}
this.status = CONNECTING
const socket = new SockJs(this.url, [], {
sessionId: () => {
return this.sessionId
},
})
this.stompClient = Stomp.over(socket)
this.stompClient.connect(
{
Cookie: document.cookie,
...(params || {}),
},
() => {
if (this.status === DISCONNECTING) {
this._connectEnded()
return
}
this.status = CONNECTED
successCb(this.stompClient)
resolve(this.stompClient)
},
e => {
this.status = FAILD
this._connectEnded()
!errorCb.executed && errorCb(e)
errorCb.executed = false
this.reConnect()
// reject(msg)
},
)
const oldCloseCB = this.stompClient.ws.onclose
this.stompClient.ws.onclose = e => {
errorCb(e)
errorCb.executed = true
oldCloseCB()
}
})
}
reConnect() {
if (!this.shouldReconnect) return
this.stopTimeout()
this.disconnect()
this.shouldReconnect = true
this.timeout = setTimeout(async () => {
// 断网情况下,不做实际重连操作,只是循环调用等待联网后再实际重连
// 但只在chrome下做此处理,因为此属性在其他浏览器下可能不支持
if (isChrome() && !navigator.onLine) {
logger.warn('网络已断开,重连失败')
this.reConnect()
return
}
await this.connect(
this.params,
this.successCb,
this.errorCb,
)
// 自定义的重连回调
// for example:
// const ws = new ReconnetWebsocket(
// this.host + '/apiEngine/webSocket/userClient',
// )
// ws.onReconnect = () => {
// this.$emit('userClient-reconnected')
// }
if (this.onReconnect) {
this.onReconnect()
}
}, 1500)
}
stopReconnect() {
this.shouldReconnect = false
this.stopTimeout()
}
startReconnect() {
this.shouldReconnect = true
this.reConnect()
}
stopTimeout() {
if (this.timeout) {
clearTimeout(this.timeout)
this.timeout = null
}
}
disconnect() {
if (this.status === DISCONNECTING || this.status === DISCONNECTED) {
logger.log('ws already disconnected in util', this.status, this.url)
return
}
logger.log('disconnect ws in util', this.url)
this.status = DISCONNECTING
/**
* 主动调用disconnect
*
* 说明不需要重连
*/
this.shouldReconnect = false
return new Promise((resolve, reject) => {
const disconnected = () => {
this.status = DISCONNECTED
resolve()
}
if (this.stompClient) {
try {
this.stompClient.disconnect(disconnected)
} catch (e) {
logger.log('--------catch error disconnect------------', e)
/**
* stompClient的disconnect方法会给服务器发送一个disconnect帧,所以会调用sockjs的send方法
* 当ws处于连接中状态时,sockjs的send方法会抛错,导致ws关闭过程中断
* 而且ws此时会继续连接,最后会变成连接中状态
* 所以需要等待连接完毕(成功/失败)再去断开
*/
if (
String(e).includes(
'InvalidStateError: The connection has not been established yet',
)
) {
this._onConnectEnd(() => {
logger.log('------------finally disconnect----------')
this.stompClient.disconnect(disconnected)
})
}
}
} else {
reject('ws 对象不存在')
}
})
}
}