uniapp中websocket的使用还是比较简单的,自己试验了一下,封装了一个类,记录了一下,方便以后使用。
一、封装的类
const _WEBSOCKET = {
//是否打开连接
isOpen: false,
//连接socket
connectSocket(url,successFunc = null, errorFunc = null) {
try {
//连接socket
uni.connectSocket({
url,
success() {
console.log('websocket连接成功!')
}
})
//监听socket连接
uni.onSocketOpen((res) => {
this.isOpen = true
console.log('WebSocket连接已打开!')
if (successFunc) {
successFunc(res)
}
})
//监听socket连接失败
uni.onSocketError((res) => {
this.isOpen = false
console.log('WebSocket连接打开失败,请检查!')
if (errorFunc) {
errorFunc(res)
}
})
//监听收到消息
uni.onSocketMessage((res) => {
console.log('收到服务器内容:' + res.data)
})
//监听socket关闭
uni.onSocketClose((res) => {
console.log('WebSocket 已关闭!')
this.isOpen = false
})
} catch (error) {
console.log('err:' + error)
}
},
//发送消息
sendMessage(msg = '', successFunc = null, errorFunc = null) {
if (!this.isOpen || !msg) {
if (errorFunc) {
errorFunc('未传消息内容或连接未打开!')
}
return
}
uni.sendSocketMessage({
data: msg,
success(res) {
console.log('消息发送成功!')
if (successFunc) {
successFunc(res)
}
},
fail(err) {
console.log('消息发送失败!')
if (errorFunc) {
errorFunc(err)
}
}
})
},
//关闭连接
closeSocket() {
if (!this.isOpen) {
return
}
//关闭socket连接
uni.closeSocket()
}
}
export default _WEBSOCKET
二、在App.vue中使用
<script>
//导入websocket对象
import websocket from '@/common/services/websocket'
//定义定时器
let globalTimer = null
export default {
onShow() {
try {
//建立socket连接
websocket.connectSocket('wss://xxxxxxxx.com',() => {
//如果连接成功则发送心跳检测
this.heartBeatTest()
})
} catch (error) {
console.log('App err:' + error)
}
},
onHide() {
//关闭socket
websocket.closeSocket()
},
methods: {
//心跳检测
heartBeatTest() {
//清除定时器
clearInterval(globalTimer)
//开启定时器定时检测心跳
globalTimer = setInterval(() => {
//发送消息给服务端
websocket.sendMessage(
JSON.stringify({ action: 'ping'}), //与服务端约定好消息格式
null,
() => {
//如果失败则清除定时器
clearInterval(globalTimer)
}
)
}, 10000)
}
}
}
</script>
三、示例效果

网友评论