创建一个Scoket.js
class webSocketClass {constructor(url, time) {this.url = urlthis.data = nullthis.isCreate = false // WebSocket 是否创建成功this.isConnect = false // 是否已经连接this.isInitiative = false // 是否主动断开this.timeoutNumber = time // 心跳检测间隔this.heartbeatTimer = null // 心跳检测定时器this.reconnectTimer = null // 断线重连定时器this.socketExamples = null // websocket实例this.againTime = 3 // 重连等待时间(单位秒)}// 初始化websocket连接initSocket(courseid,uid) {const _this = thisthis.socketExamples = uni.connectSocket({url: _this.url,header: {'content-type': 'application/json'},success: (res) => {_this.isCreate = true},fail: (rej) => {console.error(rej)_this.isCreate = false}})this.createSocket(courseid,uid)}// 创建websocket连接createSocket(courseid,uid) {if (this.isCreate) {console.log('WebSocket 开始初始化')// 监听 WebSocket 连接打开事件try {this.socketExamples.onOpen(() => {//初次登录时发送登录链接if(courseid&&uid){let data = {courseid: courseid,uid:uid,type:'login'}this.sendMsg(data)}console.log('WebSocket 连接成功')this.isConnect = trueclearInterval(this.heartbeatTimer)clearTimeout(this.reconnectTimer)// 打开心跳检测// this.heartbeatCheck()})// 监听 WebSocket 接受到服务器的消息事件this.socketExamples.onMessage((res) => {uni.$emit('message', res)})// 监听 WebSocket 连接关闭事件this.socketExamples.onClose(() => {console.log('WebSocket 关闭了')this.isConnect = falsethis.reconnect()})// 监听 WebSocket 错误事件this.socketExamples.onError((res) => {console.log('WebSocket 出错了')console.log(res)this.isInitiative = false})} catch (error) {console.warn(error)}} else {console.warn('WebSocket 初始化失败!')}}// 发送消息sendMsg(value) {const param = JSON.stringify(value)return new Promise((resolve, reject) => {this.socketExamples.send({data: param,success() {//存储发送消息,不保存登录消息let weChatList = uni.getStorageSync('weChatList')if(weChatList){if(value.type=='msg'){weChatList.push(value)uni.setStorageSync('weChatList',weChatList)}}else{if(value.type=='msg'){let msgContent=[]msgContent.push(value)uni.setStorageSync('weChatList',msgContent)}}console.log('消息发送成功')resolve(true)},fail(error) {console.log('消息发送失败')reject(error)}})})}// 开启心跳检测heartbeatCheck() {console.log('开启心跳')this.data = { state: 1, method: 'heartbeat' }this.heartbeatTimer = setInterval(() => {this.sendMsg(this.data)}, this.timeoutNumber * 1000)}// 重新连接reconnect() {// 停止发送心跳clearTimeout(this.reconnectTimer)clearInterval(this.heartbeatTimer)// 如果不是人为关闭的话,进行重连if (!this.isInitiative) {this.reconnectTimer = setTimeout(() => {this.initSocket()}, this.againTime * 1000)}}// 关闭 WebSocket 连接closeSocket(reason = '关闭') {const _this = thisthis.socketExamples.close({reason,success() {_this.data = null_this.isCreate = false_this.isConnect = false_this.isInitiative = true_this.socketExamples = nullclearInterval(_this.heartbeatTimer)clearTimeout(_this.reconnectTimer)console.log('关闭 WebSocket 成功')},fail() {console.log('关闭 WebSocket 失败')}})}
}export default webSocketClass
import WebSocketClass from '@/subPages/livePages/liveCourse/js/Socket.js'const app = getApp();data(){},onShow(){this.$nextTick(()=>{// 如果已经有sockt实例if (app.globalData.socketObj) {// 如果sockt实例未连接if (!app.globalData.socketObj.isConnect) {if(data.islive == 1){app.globalData.socketObj.initSocket(this.courseid,data.telecast_user.user_id)}}} else {// 如果没有sockt实例,则创建const path = `地址`app.globalData.socketObj = new WebSocketClass(`${path}`,60)app.globalData.socketObj.initSocket(this.courseid,data.telecast_user.user_id) }})},onLoad(){uni.$on('message', this.getMessage)},onUnLoad(){//清空存储消息记录uni.removeStorageSync('weChatList')// 关闭websocketuni.$off('message', this.getMessage)app.globalData.socketObj.closeSocket()},methods:{getMessage(msg) {if(msg.data){let msgItem = JSON.parse(JSON.parse(msg.data).data)let weChatList = uni.getStorageSync('weChatList')this.weChatList = weChatList}},}