1.创建webSocketHttp.js文件
//导入系统方法
class webSocket {
//是否打开连接
isOpen = false
//全局的定时器
globalTimer = null
//存储task对象
socketTask = null
//连接socket
async connectSocket(
linkMark, //连接标识
option = {}, //连接需要带的额外的参数
successFunc = null, //连接成功回调
errorFunc = null, //连接错误回调
receiveFunc = null, //接收到消息回调
closeFunc = null //连接关闭回调
) {
try {
//如果连接已存在并且已经打开就不再连接
if (this.socketTask && this.isOpen) {
return
}
//获取对应的长连接URL
let url = linkMark
//建立连接
this.socketTask = uni.connectSocket({
url,
success() {
console.log('websocket:' + linkMark + '连接成功!')
}
})
//监听打开事件
this.socketTask.onOpen((res) => {
console.log('websocket:' + linkMark + '打开成功!')
this.isOpen = true
this.sendMessage(option, null, () => {})
//开启心跳检测
this.heartBeatTest(option)
//回调
if (successFunc) {
successFunc(res)
}
})
//监听连接关闭事件
this.socketTask.onClose(() => {
console.log('websocket:' + linkMark + '已关闭!')
this.isOpen = false
this.closeSocket()
if (closeFunc) {
closeFunc()
}
})
//监听websocket错误事件
this.socketTask.onError((res) => {
console.log('websocket:' + linkMark + '已出错!')
this.isOpen = false
if (errorFunc) {
errorFunc(res)
}
})
//监听接收到的消息
this.socketTask.onMessage((res) => {
// console.log('监听接收到的消息')
if (receiveFunc) {
receiveFunc(res)
}
})
} catch (error) {
console.log('websocket:' + linkMark + '异常:' + error)
}
}
//发送消息(msg是一个对象)
sendMessage(msg = null, successFunc = null, errorFunc = null) {
if (!this.socketTask || !this.isOpen || !msg) {
if (errorFunc) {
errorFunc('未传消息内容或连接未打开!')
}
return
}
this.socketTask.send({
data: JSON.stringify(msg),
success(res) {
if (successFunc) {
successFunc(res)
}
},fail(err) {
if (errorFunc) {
errorFunc(err)
}
}
})
}
//关闭连接
closeSocket() {
console.log('关闭链接')
if (!this.socketTask || !this.isOpen) {
return
}
//关闭socket连接
this.socketTask.close()
//设置关闭状态
this.isOpen = false
}
//心跳检测
heartBeatTest(option) {
//清除定时器
clearInterval(this.globalTimer)
this.globalTimer = setInterval(() => {
this.sendMessage({code:10015}, null, () => {
//如果失败则清除定时器
clearInterval(this.globalTimer)
})
}, 10000)
}
}
export default webSocket
2.在需要使用的的页面引入(也可全局引入)
import webSocket from '@/utils/webscoketHttp.js'
const websocket = new webSocket()
3.创建连接监听心跳
buildWebSocket() {
let that = this;
try {
websocket.connectSocket(
getApp().globalData.wsApiUrl,//连接标识
{ //可以传递额外的参数
token:'',
code:10080,//活跃通道
},
null,
() => {
//出错的回调,重新建立连接
// setTimeout(() => {
// that.buildWebSocket()
// }, 5000)
},(msg) => {
//根据接收到的消息来处理业务逻辑
//连接回调
let res = JSON.parse(msg.data)
},() => {
//关闭了就重新连接
// setTimeout(() => {
// this.buildWebSocket()
// }, 2000)
})
} catch (error) {
console.log('live socket err:' + error)
}
},