H5 WebSocket
# 小程序WebSocket
- websocket服务,云托管底层会有健康检查尝试连接,属于正常的请求;你可以通过请求的header进行识别进行过滤,正常的websocket连接请求会带
Connection: Upgrade
、Upgrade: websocket
这两个header。可根据header的差异在代码中过滤请求。 - websocket目前只支持wss方式连接。
# 初始化WebSocket
// 小程序与设备建立WebSocket连接
const initWebSocket = () => {
websocketConnect()
}
1
2
3
4
2
3
4
# 连接WebSocket
// WebSocket是否处于连接状态
let socketOpen = ref(false)
let websockSign = ref(null)
// 连接WebSocket
const websocketConnect = () => {
const url = `xxx`
websockSign.value = new WebSocket(url) // WebSocket 服务器地址
if (
websockSign.value.readyState !== null &&
websockSign.value.readyState == 1
) {
//避免重复链接
console.log('websocket 连接已存在...')
} else {
websockSign.value.onopen = (e) => websocketOnopen(e)
websockSign.value.onerror = (e) => websocketOnerror(e)
websockSign.value.onmessage = (e) => websocketOnmessage(e)
websockSign.value.onclose = (e) => websocketOnclose(e)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 监听WebSocket连接打开事件
// 监听WebSocket连接打开事件
const websocketOnopen = () => {
console.log('WebSocket连接成功')
if (!socketOpen.value && chatText.value) {
socketOpen.value = true
saveAndSendChat()
} else {
socketOpen.value = true
}
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 监听WebSocket关闭事件
// 监听WebSocket关闭事件
const websocketOnclose = () => {
if (res?.code !== 1000) {
console.log('WebSocket 非正常断开重连...')
socketOpen.value = false
reConnect()
}
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 监听WebSocket错误事件
// 监听WebSocket错误事件
const websocketOnerror = () => {
if (res?.code !== 1000) {
console.log('WebSocket 非正常断开重连...')
socketOpen.value = false
reConnect()
}
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 关闭WebSocket连接
// 关闭WebSocket连接
const closeWebSocket = () => {
uni.closeSocket({
code: 1000,
reason: 'close reason from client',
success: (res) => {},
fail: (error) => {}
})
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 尝试重连WebSocket
// WebSocket重连状态
let lockReconnect = ref(false)
// 重连WebSocket定时器
let websocketTimer = ref(null)
// 尝试重连WebSocket
const reConnect = () => {
if (lockReconnect.value) return
reConnect.value = true
// 停止发送心跳
if (heartbeatTimer.value) {
clearTimeout(heartbeatTimer.value)
heartbeatTimer.value = null
}
// 没连接上会一直重连,设置延迟避免请求过多
websocketTimer.value = setTimeout(() => {
console.log('尝试重连...')
initWebSocket()
// WebSocket断开时需要重新请求设备控件状态
getDevices()
lockReconnect.value = false
clearTimeout(websocketTimer.value)
}, 5000)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 向后端发送命令
// 向后端发送命令(发送数据,需要先uni.connectSocket,并在uni.onSocketOpen回调之后才能发送)
const sendMsg = (type) => {
const params = {
token,
serial_no
}
// 处理发送数据:连接WebSocket发送token、serial_no
let data = null
if (type === 'heartbeat') {
data = 'heartbeat'
} else {
data = JSON.stringify(params)
}
console.log('发送的数据:', data)
// 开启心跳检测
heartbeatCheck()
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 心跳检测
// 心跳检测间隔(单位秒):WebSocket默认一分钟内未通信会自动断开连接
let timeoutNumber = 30
// 心跳检查定时器
let heartbeatTimer = ref(null)
// 开启心跳检测
const heartbeatCheck = () => {
if (heartbeatTimer.value === null) {
heartbeatTimer.value = setTimeout(() => {
console.log('心跳检测')
sendMsg('heartbeat')
clearTimeout(heartbeatTimer.value)
heartbeatTimer.value = null
heartbeatCheck()
}, timeoutNumber * 1000)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
编辑 (opens new window)