【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
				}
			},
	}
相关推荐
郑州光合科技余经理1 小时前
技术视角:海外版一站式同城生活服务平台源码解析
java·开发语言·uni-app·php·排序算法·objective-c·生活
wangdaoyin20103 小时前
UniApp中使用LivePlayer进行视频或在流媒体播放
uni-app·liveplayer·h5播放视频
2501_915106323 小时前
App HTTPS 抓包实战解析,从代理调试到真实网络流量观察的完整抓包思路
网络协议·http·ios·小程序·https·uni-app·iphone
游戏开发爱好者85 小时前
苹果App Store应用程序上架方式全面指南
android·小程序·https·uni-app·iphone·webview
2501_916008895 小时前
深入理解 iPhone 文件管理,从沙盒结构到开发调试的多工具协同实践
android·ios·小程序·https·uni-app·iphone·webview
一室易安5 小时前
解决使用 UniApp 搭配 Vue3 小程序开始 使用uview-plus 的返回顶部up-back-top中onPageScroll 不触发的问题
小程序·uni-app
yilan_n6 小时前
鸿蒙应用上传
vue.js·华为·uni-app
yilan_n6 小时前
【UniApp实战】手撸面包屑导航与路由管理 (拒绝页面闪烁)
前端·javascript·vue.js·uni-app·gitcode
一室易安6 小时前
uniapp+vue3 微信小程序中 页面切换tab 页面滚动到指定锚点位置,滚动页面时候到达指定锚点位置吸顶tab 会自动进行切换
微信小程序·uni-app·notepad++
2501_916007476 小时前
没有 Mac,如何在 Windows 上架 iOS 应用?一套可落地的工程方案
android·macos·ios·小程序·uni-app·iphone·webview