You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

110 lines
2.1 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import config from "../config.js"
let websocket = {}
// 服务器接口地址
websocket.url = config.wss
// 链接是否打开
websocket.isSocketOpen = false
// 心跳定时每30s执行一次
websocket.timer = ''
// 每Xs执行一次心跳数据发送
websocket.seconds = 30
/**
* 创建链接并监听打开&报错事件&关闭事件
* @date 2022-05-17
*/
websocket.init = function() {
return new Promise((resolve, reject) => {
// 创建一个 WebSocket 连接。
uni.connectSocket({
url: this.url,
success: (res) => {
console.log('connectSocketSuccess', res)
},
fail: (res) => {
console.log('connectSocketFail', res)
},
complete: (res) => {
// console.log('connectSocketComplete', res)
}
})
// 监听WebSocket连接打开事件
uni.onSocketOpen((res) => {
console.log('onSocketOpen', res)
this.isSocketOpen = true
//发送心跳数据
this.timer = setInterval(() => {
this.sendMessage({
type: 'heart_beat',
send_type: 'to_self',
data: {
content: '发送心跳数据'
}
})
}, this.seconds * 1000)
resolve(res)
})
// 监听WebSocket错误
uni.onSocketError((res) => {
console.log('onSocketError', res)
reject(res)
})
// 监听WebSocket关闭
uni.onSocketClose((res) => {
console.log('onSocketClose', res)
this.isSocketOpen = false
// 关闭心跳
if (this.timer) {
clearInterval(this.timer)
}
reject(res)
})
})
}
/**
* 通过 WebSocket 连接发送数据
* @date 2022-05-18
*/
websocket.sendMessage = function(data) {
return new Promise((resolve, reject) => {
if (!this.isSocketOpen) {
reject('当前websocket连接未打开')
return false
}
uni.sendSocketMessage({
data: JSON.stringify(data),
success: (res) => {
console.log('sendMessageSuccess', res)
resolve(res)
},
fail: (res) => {
console.log('sendMessageFail', res)
reject(res)
}
})
})
}
/**
* 关闭 WebSocket 连接
* @date 2022-05-18
*/
websocket.closeSocket = function() {
// 更改websocket状态为关闭
this.isSocketOpen = false
uni.closeSocket()
}
export default websocket