1、新建js文件封装websocket.js
const WEBSOCKET = {
//是否打开连接
socketOpen: false,
//连接socket
/*
url:链接地址 wss://xxxxxxxx.com
socketMessageFunc:收到服务器内容回调
*/
connectSocket(url, socketMessageFunc = null) {
try {
//连接socket
uni.connectSocket({
url,
success() {
console.log('websocket连接成功!')
}
})
//监听socket连接
uni.onSocketOpen((res) => {
this.socketOpen = true
console.log('WebSocket连接已打开!',res)
})
//监听socket连接失败
uni.onSocketError((res) => {
this.socketOpen = false
console.log('WebSocket连接打开失败,请检查!',res)
})
//监听收到消息
uni.onSocketMessage((res) => {
console.log('收到服务器内容:' + res.data)
if(socketMessageFunc){
socketMessageFunc(res.data)
}
})
//监听socket关闭
uni.onSocketClose(() => {
console.log('WebSocket 已关闭!')
this.socketOpen = false
})
} catch (error) {
console.log('err:' + error)
}
},
//发送消息
/*
msg:字符串 JSON.stringify({
"userId": this.uid,
"targetIds": targetId,
"data":'哈哈哈'
})
successFunc:成功回调函数
errorFunc:失败回调函数
*/
sendMessage(msg = '', successFunc = null, errorFunc = null) {
if (!this.socketOpen || !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.socketOpen) {
return
}
//关闭socket连接
uni.closeSocket()
}
}
export default WEBSOCKET
2、单页面使用
<template>
<view>
<button type="primary" @click="heartBeatTest">开启定时器定时检测心跳</button>
</view>
</template>
<script>
//导入websocket对象
import websocket from '@/utils/websocket'
//定义定时器
let globalTimer = null
export default {
onLoad() {
try {
//建立socket连接
websocket.connectSocket('wss://xxxxxxxx.com', (res) => {
console.log('收到内容:', res);
//做一些处理、方法调用
})
} catch (error) {
console.log('error:' + error)
}
},
onUnload() {
//关闭socket
websocket.closeSocket()
},
methods: {
heartBeatTest() {
//清除定时器
if(globalTimer){
clearInterval(globalTimer)
globalTimer = null
}
globalTimer = setInterval(() => {
//发送消息给服务端
websocket.sendMessage(
JSON.stringify({
"userId": '001',
"targetIds": '1234',
"data": '哈哈哈'
}), //与服务端约定好消息格式
(res ) => {
console.log('消息发送成功!',res)
},
(err) => {
console.log('消息发送失败!',err)
//如果失败则清除定时器
clearInterval(globalTimer)
}
)
}, 10000)
}
}
}
</script>
<style lang="scss">
</style>