SocketIoClient.js
3.53 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
/*
* socket.io 客户端封装(与 ws/Ws.js 同协议,供 Demo / 业务推流使用)
* 注意:项目服务端是 socket.io,不能用 uni.connectSocket 直连
*/
import io from '@/uni_modules/hyoga-uni-socket_io/uni-socket.io.js'
import config from '@/config.js'
import { WsTyps } from '@/utils/common'
import { serializeIfObject } from '@/utils/utils.js'
import { loginDevice } from './wsAuth.js'
class SocketIoClient {
constructor(options = {}) {
this._tag = options.logTag || 'SocketIo'
this._ws = null
this._deviceId = null
this._token = null
this._onMessage = null
this._connected = false
}
get isConnected() {
return this._connected && this._ws != null
}
get deviceId() {
return this._deviceId
}
onMessage(handler) {
this._onMessage = typeof handler === 'function' ? handler : null
}
/**
* 登录并连接 socket.io(与 Ws.js 相同 path / auth)
*/
async connect() {
if (this.isConnected) {
return true
}
const { code, data } = await loginDevice()
if (code != 200) {
throw new Error(`WS 登录失败 code=${code}`)
}
this._deviceId = data.id
this._token = data.token
this._log('info', `登录成功 deviceId=${this._deviceId}`)
return new Promise((resolve, reject) => {
const socket = io(config.SOCKET_SERVER, {
path: '/websocket/',
auth: { token: this._token, deviceId: this._deviceId },
transports: ['websocket'],
timeout: 5000
})
const timer = setTimeout(() => {
cleanup()
reject(new Error('socket.io 连接超时'))
}, 8000)
const onConnect = () => {
cleanup()
this._ws = socket
this._connected = true
this._log('info', 'socket.io 已连接')
this._bindMessage()
resolve(true)
}
const onError = (err) => {
cleanup()
this._log('error', `socket.io 错误 ${serializeIfObject(err)}`)
reject(err || new Error('socket.io error'))
}
const onDisconnect = () => {
this._connected = false
this._log('warn', 'socket.io 已断开')
}
const cleanup = () => {
clearTimeout(timer)
socket.off(WsTyps.Connected, onConnect)
socket.off(WsTyps.Eroor, onError)
}
socket.on(WsTyps.Connected, onConnect)
socket.on(WsTyps.Eroor, onError)
socket.on(WsTyps.Disconnected, onDisconnect)
this._log('info', `连接 socket.io -> ${config.SOCKET_SERVER}/websocket/`)
})
}
_bindMessage() {
if (!this._ws || !this._onMessage) return
this._ws.on(WsTyps.MessageTypes.Private, (data) => {
this._onMessage(data)
})
}
/**
* 发送消息(默认 private 频道,自动带 device_id)
* @param {object} data
*/
send(data, type = WsTyps.MessageTypes.Private) {
if (!this.isConnected) {
return Promise.reject(new Error('socket.io 未连接'))
}
const payload = { device_id: this._deviceId, ...data }
this._log('debug', `发送 => ${serializeIfObject(data).slice(0, 200)}`)
this._ws.emit(type, payload)
return Promise.resolve({ errMsg: 'emit:ok' })
}
disconnect() {
this._connected = false
if (this._ws) {
try {
this._ws.disconnect()
} catch (_) {
/* ignore */
}
this._ws = null
}
this._onMessage = null
this._log('info', 'socket.io 已关闭')
}
_log(level, msg) {
const text = `[${this._tag}] ${msg}`
uni.$logger?.local?.[level]?.(text) || console.log(text)
}
}
export default SocketIoClient