NativeWsClient.js
8.43 KB
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
/*
* 原生 WebSocket 客户端(SocketTask)
* 协议对齐 venus uniapp-x-tape/ws/Ws.uts
* API 对齐 https://uniapp.dcloud.net.cn/api/request/websocket.html
*
* - connect(): 走 /login 拿 token/deviceId,然后按 `NATIVE_WS_BASE`(若设置)或 `SOCKET_SERVER + WS_NATIVE_PATH` 连接
* - connectDirect(url): 不登录,直接连接指定 url(用于独立服务)
*/
import config from '@/config.js'
import { serializeIfObject } from '@/utils/utils.js'
import { loginDevice } from './wsAuth.js'
import {
buildAuthenticatedWsUrl,
getNativeWsBase,
normalizeWsUrl,
pickLoginWsUrl
} from './wsConfig.js'
import { normalizeWsPayload } from './wsMessage.js'
import { createSocketTask } from './connectSocketTask.js'
const DEFAULT_TYPE = 'private'
function formatSocketErr(err) {
if (!err) return 'unknown'
if (typeof err === 'string') return err
if (err.errMsg) return err.errMsg
if (err.message) return err.message
const raw = serializeIfObject(err)
return raw === '{}' ? 'WebSocket 连接失败(请确认 utils/socket/wsConfig.js 中 NATIVE_WS_BASE)' : raw
}
class NativeWsClient {
constructor() {
this.wsAddress = getNativeWsBase() || config.SOCKET_SERVER
this.token = ''
this.deviceId = ''
this.onMessage = null
this.socketTask = null
this._connected = false
this._manualClose = false
this._reconnectTimer = null
this._reconnectCount = 0
this._isReconnecting = false
this._directUrl = ''
}
get isConnected() {
return this._connected && this.socketTask != null
}
/** 直连指定 ws 地址(无登录鉴权,用于音频对话等独立服务) */
async connectDirect(url) {
const target = normalizeWsUrl(url)
if (!target) {
throw new Error('connectDirect 缺少 url')
}
this._manualClose = false
this._directUrl = target
await this.close(1000, 'reconnect', false).catch(() => {})
this._manualClose = false
try {
await this._connectSocketByUrl(target)
} catch (e) {
this._log('error', `connectDirect 失败: ${e.message}`)
throw e
}
}
/** 发送纯 JSON 字符串,不附加 device_id 等字段 */
sendJson(obj) {
return this.send(JSON.stringify(obj))
}
async connect() {
this._manualClose = false
this._directUrl = ''
try {
const loginRes = await loginDevice()
const code = loginRes?.code
if (code != 200 && code != 0) {
throw new Error(`登录失败 code=${code}`)
}
const data = loginRes.data || {}
this.deviceId = data.id
this.token = data.token
if (!this.deviceId || !this.token) {
throw new Error('登录返回缺少 id 或 token')
}
const wsFromLogin = pickLoginWsUrl(data)
if (wsFromLogin) {
this.wsAddress = wsFromLogin
}
await this._createSocket()
} catch (e) {
this._log('error', `connect 失败: ${e.message}`)
this._scheduleReconnect()
throw e
}
}
send(data, type = DEFAULT_TYPE) {
if (!this.isConnected) {
this._log('warn', '未连接,send 忽略')
return Promise.resolve(false)
}
let packet
if (typeof data === 'string') {
packet = data
} else if (data instanceof ArrayBuffer) {
packet = data
} else if (ArrayBuffer.isView(data)) {
packet = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength)
} else {
packet = JSON.stringify({
...data,
device_id: this.deviceId,
type: data.type || type
})
}
return new Promise((resolve) => {
this.socketTask.send({
data: packet,
success: () => resolve(true),
fail: (err) => {
this._log('warn', `send 失败: ${serializeIfObject(err)}`)
resolve(false)
}
})
})
}
async close(code = 1000, reason = 'manual close', manual = true) {
this._manualClose = manual
this._clearReconnectTimer()
this._connected = false
const task = this.socketTask
this.socketTask = null
if (!task) return
await new Promise((resolve) => {
task.close({ code, reason, complete: () => resolve() })
})
}
async waitUntilConnected(timeoutMs = 15000) {
if (this.isConnected) return true
const start = Date.now()
while (Date.now() - start < timeoutMs) {
if (this.isConnected) return true
await new Promise((r) => setTimeout(r, 200))
}
return false
}
async _createSocket() {
await this.close(1000, 'reconnect', false).catch(() => {})
this._manualClose = false
const url = buildAuthenticatedWsUrl(this.wsAddress, this.token, this.deviceId)
await this._connectSocketByUrl(url)
}
_connectSocketByUrl(targetUrl) {
this._log(
'info',
`连接地址 ${targetUrl}(login=${config.HTTP_SERVER})`
)
return new Promise((resolve, reject) => {
let opened = false
let settled = false
const timer = setTimeout(() => {
if (settled) return
settled = true
reject(new Error(`连接超时: ${targetUrl}`))
}, 8000)
const finishOpen = () => {
if (settled) return
opened = true
settled = true
clearTimeout(timer)
this._reconnectCount = 0
this._isReconnecting = false
this._connected = true
this._log('warn', '连接成功')
resolve()
}
const failEarly = (err) => {
if (settled) return
settled = true
clearTimeout(timer)
reject(new Error(err?.message || serializeIfObject(err)))
}
let socketTask
try {
socketTask = createSocketTask({
url: targetUrl,
fail: (err) => failEarly(err)
})
} catch (e) {
failEarly(e)
return
}
this.socketTask = socketTask
socketTask.onOpen(() => finishOpen())
socketTask.onMessage((event) => this._handleMessage(event?.data))
socketTask.onError((err) => {
this._log('error', `异常 ${formatSocketErr(err)}`)
if (!opened && !settled) {
failEarly(new Error(`onError: ${formatSocketErr(err)}`))
} else if (opened && !this._manualClose) {
this._scheduleReconnect()
}
})
socketTask.onClose((res) => {
this._connected = false
this.socketTask = null
this._log('warn', `断开 ${serializeIfObject(res)}`)
if (!opened && !settled) {
const closeHint = res?.code === 1006 || !res?.code
? '(握手失败,常见原因:路径 404 或服务端仅支持 socket.io)'
: ''
failEarly(new Error(`onClose before open: ${serializeIfObject(res)}${closeHint}`))
return
}
if (!this._manualClose) {
this._scheduleReconnect()
}
})
})
}
_handleMessage(raw) {
const data = normalizeWsPayload(raw)
this._log('info', `收到 <= ${JSON.stringify(data).slice(0, 240)}`)
if (data.errorCode && data.errorCode == 907) {
this._log('warn', 'Token 过期,准备重连')
this._scheduleReconnect(true)
return
}
this.onMessage && this.onMessage(data)
}
_scheduleReconnect(force = false) {
if (this._manualClose) return
if (this._isReconnecting && !force) return
this._isReconnecting = true
this._clearReconnectTimer()
this._reconnectCount += 1
const delay = Math.min(30000, this._reconnectCount * 2000)
this._log('warn', `${delay}ms 后第 ${this._reconnectCount} 次重连`)
this._reconnectTimer = setTimeout(() => {
this._reconnectTimer = null
const reconnect = this._directUrl
? () => this.connectDirect(this._directUrl)
: () => this.connect()
reconnect().catch(() => {})
}, delay)
}
_clearReconnectTimer() {
if (this._reconnectTimer != null) {
clearTimeout(this._reconnectTimer)
this._reconnectTimer = null
}
}
_log(level, msg) {
const text = `[NativeWs] ${msg}`
const logger = uni.$logger?.local
if (logger?.[level]) {
logger[level](text)
} else if (level === 'error') {
console.error(text)
} else if (level === 'warn') {
console.warn(text)
} else {
console.log(text)
}
}
}
let _instance = null
NativeWsClient.getInstance = function getInstance() {
if (!_instance) {
_instance = new NativeWsClient()
}
return _instance
}
NativeWsClient.resetInstance = function resetInstance() {
if (_instance) {
_instance.close().catch(() => {})
_instance = null
}
}
export default NativeWsClient