美文网首页微信小程序
uniapp-websocket的封装

uniapp-websocket的封装

作者: Morbid_D | 来源:发表于2022-09-01 17:33 被阅读0次

1.新建webSocket.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() {

    const _this = this

    this.socketExamples = uni.connectSocket({

      url: _this.url,

      header: {

        'content-type': 'application/json'

      },

      success: (res) => {

        _this.isCreate = true

        console.log(res)

      },

      fail: (rej) => {

        console.error(rej)

        _this.isCreate = false

      }

    })

    this.createSocket()

  }

  // 创建websocket连接

  createSocket() {

    if (this.isCreate) {

      console.log('WebSocket 开始初始化')

      // 监听 WebSocket 连接打开事件

      try {

        this.socketExamples.onOpen(() => {

          console.log('WebSocket 连接成功')

          this.isConnect = true

          clearInterval(this.heartbeatTimer)

          clearTimeout(this.reconnectTimer)

          // 打开心跳检测

          this.heartbeatCheck()

        })

        // 监听 WebSocket 接受到服务器的消息事件

        this.socketExamples.onMessage((res) => {

          console.log('收到消息')

          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() {

          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

2.在App.vue的globalData添加===》socketObj:null

3.引用 import WebSocketClass from '../../common/webSocket'

4.使用

    onLoad(){uni.$on('message', this.getMessage)},

onUnload() {

  uni.$off('message', this.getMessage)

},

methods:{getMessage(msg) {}

console.log(msg)

},

在需要使用的地方使用 

if (getApp().globalData.socketObj) {

// 如果sockt实例未连接

if (!getApp().globalData.socketObj.isConnect) {

  getApp().globalData.socketObj.initSocket()

}

  } else {

// 如果没有sockt实例,则创建

getApp().globalData.socketObj = new WebSocketClass(

  `wss:这里是地址`,

  60

)

getApp().globalData.socketObj.initSocket()

  }

相关文章

  • JavaScript面向对象与设计模式

    1. 面向对象 1.1 封装 封装的目的在于将信息隐藏。广义的封装不仅包括封装数据和封装实现,还包括封装类型和封装...

  • 02.OOP面向对象-3.一些理解

    对封装的理解?封装,类本身就是一个封装,封装了属性和方法。方法也是封装,对一些业务逻辑的封装。私有也是封装,将一些...

  • node学习4

    Nodejs 路由模块封装、封装仿照 express 的路由 Nodejs 路由模块封装 封装仿照 express...

  • python 文件及文件夹的操作和异常捕获

    1、面向对象的特征:封装、继承、多态 1.1、封装: 函数一种封装,封装了一些逻辑代码 类也是一种封装,封装属性和...

  • view的封装

    封装view较为简单,封装tableview比较麻烦,封装tableview的方法后面会有。 view的封装 如果...

  • 面向对象02-封装

    面向对象02-封装 [TOC] 好处 广义的封装:方法、类、包狭义的封装:类中的属性的封装 封装的具体体现 规范 代码

  • JavaScript的面向对象--封装的实现、类型、变化

    封装的目的是将信息隐藏。一般而言,我们讨论的封装是封装数据和封装实现。这里将讨论更广义的封装,不仅包括封装数据和封...

  • 2018-03-17

    Python的封装和继承 1、封装顾名思义,就是把内容封装好,再调用封装好的内容。封装分为两步:第一步为封装内容第...

  • MVVM在网络中应用(OkHttp+Retrofit+Gson+

    1.封装请求地址常量类 2.封装网络工具类 3.封装接口类 4.封装DTO类——即返回的数据封装模型 5.封装请求...

  • 封装微信小程序请求

    封装wx.request 封装api 封装请求调用

网友评论

    本文标题:uniapp-websocket的封装

    本文链接:https://www.haomeiwen.com/subject/bekynrtx.html