【uniapp小程序-wesocket的使用】

创建一个Scoket.js

js 复制代码
class webSocketClass {
  constructor(url, time) {
    this.url = url
    this.data = null
    this.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 = this
    this.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 = true
          clearInterval(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 = false
          this.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 = this
    this.socketExamples.close({
      reason,
      success() {
        _this.data = null
        _this.isCreate = false
        _this.isConnect = false
        _this.isInitiative = true
        _this.socketExamples = null
        clearInterval(_this.heartbeatTimer)
        clearTimeout(_this.reconnectTimer)
        console.log('关闭 WebSocket 成功')
      },
      fail() {
        console.log('关闭 WebSocket 失败')
      }
    })
  }
}

export default webSocketClass
js 复制代码
	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')
		// 关闭websocket
		uni.$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
				}
			},
	}
相关推荐
2501_915921431 小时前
不用 Xcode 上架 iOS,拆分流程多工具协作完成 iOS 应用的发布准备与提交流程
android·macos·ios·小程序·uni-app·iphone·xcode
郑州光合科技余经理1 天前
可独立部署的Java同城O2O系统架构:技术落地
java·开发语言·前端·后端·小程序·系统架构·uni-app
雪芽蓝域zzs1 天前
uniapp 取消滚动条
uni-app
2401_865854881 天前
Uniapp和Flutter哪个更适合企业级开发?
flutter·uni-app
雪芽蓝域zzs1 天前
uniapp 省市区三级联动
前端·javascript·uni-app
总爱写点小BUG1 天前
UniApp 图标方案终极排坑:告别 FontClass,拥抱真 SVG 组件化
前端框架·uni-app
Rysxt_2 天前
UniApp获取安卓系统权限教程
android·uni-app
木子啊2 天前
ProCamera 智能水印相机解决方案 (UniApp)
数码相机·uni-app·水印相机·小程序水印
木子啊2 天前
Uni-app跨页面通信三剑客
前端·uni-app·传参
Rysxt_3 天前
UniApp五大UI框架与uni-ui核心区别对比
uni-app·uni-ui