【uniapp小程序-wesocket的使用】

创建一个Scoket.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
	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
				}
			},
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值