Vue中使用及封装websocket示例详解

 更新时间:2023年07月04日 12:00:42   作者:牛奔  
这篇文章主要为大家介绍了Vue中使用及封装websocket示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

简单例子

<template>
  <div class="test">
  </div>
</template>
<script>
  export default {
    name : 'test',
    data() {
      return {
        websock: null,
      }
    },
    created() {
      this.initWebSocket();
    },
    destroyed() {
      this.websock.close() //离开路由之后断开websocket连接
    },
    methods: {
      initWebSocket(){ //初始化weosocket
        const wsuri = "ws://127.0.0.1:8080";
        this.websock = new WebSocket(wsuri);
        this.websock.onmessage = this.websocketonmessage;
        this.websock.onopen = this.websocketonopen;
        this.websock.onerror = this.websocketonerror;
        this.websock.onclose = this.websocketclose;
      },
      websocketonopen(){ //连接建立之后执行send方法发送数据
        let actions = {"test":"12345"};
        this.websocketsend(JSON.stringify(actions));
      },
      websocketonerror(){//连接建立失败重连
        this.initWebSocket();
      },
      websocketonmessage(e){ //数据接收
        const redata = JSON.parse(e.data);
      },
      websocketsend(Data){//数据发送
        this.websock.send(Data);
      },
      websocketclose(e){  //关闭
        console.log('断开连接',e);
      },
    },
  }
</script>
<style lang='less'>
</style>

封装后

创建websocket.js

let Socket = ''
let setIntervalWesocketPush = null
/**
 * 建立websocket连接
 * @param {string} url ws地址
 */
export const createSocket = url => {
  Socket && Socket.close()
  if (!Socket) {
    console.log('建立websocket连接')
    Socket = new WebSocket(url)
    Socket.onopen = onopenWS
    Socket.onmessage = onmessageWS
    Socket.onerror = onerrorWS
    Socket.onclose = oncloseWS
  } else {
    console.log('websocket已连接')
  }
}
/**打开WS之后发送心跳 */
const onopenWS = () => {
  sendPing()
}
/**连接失败重连 */
const onerrorWS = () => {
  Socket.close()
  clearInterval(setIntervalWesocketPush)
  console.log('连接失败重连中')
  if (Socket.readyState !== 3) {
    Socket = null
    createSocket()
  }
}
/**WS数据接收统一处理 */
const onmessageWS = e => {
  window.dispatchEvent(new CustomEvent('onmessageWS', {
    detail: {
      data: e.data
    }
  }))
}
/**
 * 发送数据但连接未建立时进行处理等待重发
 * @param {any} message 需要发送的数据
 */
const connecting = message => {
  setTimeout(() => {
    if (Socket.readyState === 0) {
      connecting(message)
    } else {
      Socket.send(JSON.stringify(message))
    }
  }, 1000)
}
/**
 * 发送数据
 * @param {any} message 需要发送的数据
 */
export const sendWSPush = message => {
  if (Socket !== null && Socket.readyState === 3) {
    Socket.close()
    createSocket()
  } else if (Socket.readyState === 1) {
    Socket.send(JSON.stringify(message))
  } else if (Socket.readyState === 0) {
    connecting(message)
  }
}
/**断开重连 */
const oncloseWS = () => {
  clearInterval(setIntervalWesocketPush)
  console.log('websocket已断开....正在尝试重连')
  if (Socket.readyState !== 2) {
    Socket = null
    createSocket()
  }
}
/**发送心跳
 * @param {number} time 心跳间隔毫秒 默认5000
 * @param {string} ping 心跳名称 默认字符串ping
 */
export const sendPing = (time = 5000, ping = 'ping') => {
  clearInterval(setIntervalWesocketPush)
  Socket.send(ping)
  setIntervalWesocketPush = setInterval(() => {
    Socket.send(ping)
  }, time)
}

下载 (也可复制源码,放在本地,使用方式相同)

npm install @sven0706/websocket -S

使用

// 在main.js或需要使用的地方引入并建立连接
import { createSocket } from '@sven0706/websocket'
createSocket('wss://api.baidu.com')
// 发送消息
import { sendWSPush } from '@sven0706/websocket'
sendWSPush(data)
// 接收消息
const getsocketData = e => {  // 创建接收消息函数
  const data = e && e.detail.data
  console.log(data)
}
// 注册监听事件
window.addEventListener('onmessageWS', getsocketData)
// 在需要的时候卸载监听事件,比如离开页面
window.removeEventListener('onmessageWS', getsocketData)

API

仅三个api, 且一般只需要用到`createSocket`, `sendWSPush`

/**
 * 建立websocket连接
 * @param {string} url ws地址
 */
createSocket(url)
/**
 * 发送数据
 * @param {any} message 需要发送的数据
 */
 sendWSPush(message)
/**发送心跳
 * @param {number} time 心跳间隔毫秒 默认5000
 * @param {string} ping 心跳名称 默认字符串ping
 */
 sendPing()

巨人的肩膀

js websocket断线重连

js封装一个websocket

以上就是Vue中使用及封装websocket示例详解的详细内容,更多关于Vue封装websocket的资料请关注脚本之家其它相关文章!

相关文章

  • 如何在Vue3中使用视频库Video.js实现视频播放功能

    如何在Vue3中使用视频库Video.js实现视频播放功能

    在Vue3项目中集成Video.js库,可以创建强大的视频播放功能,这篇文章主要介绍了如何在Vue3中使用视频库Video.js实现视频播放功能,文中通过代码介绍的非常详细,需要的朋友可以参考下
    2024-09-09
  • vant样式不生效问题的解决办法

    vant样式不生效问题的解决办法

    这篇文章主要给大家介绍了vant样式不生效问题的解决办法,文中通过示例代码介绍的非常详细,对大家学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2023-06-06
  • vue 使用 sortable 实现 el-table 拖拽排序功能

    vue 使用 sortable 实现 el-table 拖拽排序功能

    这篇文章主要介绍了vue 使用 sortable 实现 el-table 拖拽排序功能,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-12-12
  • Vue + iView实现Excel上传功能的完整代码

    Vue + iView实现Excel上传功能的完整代码

    前一段时间项目经历了前端上传文件的过程,首先进入页面会展示默认的样子,选中要上传的excel文件,本文通过实例图文相结合给大家介绍的非常详细,需要的朋友参考下吧
    2021-06-06
  • vue2响应式的缺点影响

    vue2响应式的缺点影响

    这篇文章主要介绍了vue2响应式的缺点影响,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下
    2022-05-05
  • Vue3 KeepAlive实现原理解析

    Vue3 KeepAlive实现原理解析

    KeepAlive 是一个内置组件,那封装一个组件对于大家来说应该不会有太大的困难,它的核心逻辑在于它的 render 函数,它用 map 去记录要缓存的组件,就是 [key,vnode] 的形式,这篇文章主要介绍了Vue3 KeepAlive实现原理,需要的朋友可以参考下
    2022-09-09
  • vue中的ElementUI的使用详解

    vue中的ElementUI的使用详解

    本文通过实例代码给大家介绍了vue中的ElementUI的使用,代码简单易懂,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-10-10
  • vue如何下载本地pdf文件

    vue如何下载本地pdf文件

    这篇文章主要介绍了vue如何下载本地pdf文件问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-04-04
  • Vue2.0 实现移动端图片上传功能

    Vue2.0 实现移动端图片上传功能

    本文主要介绍VUE2.0图片上传功能的实现。原理是通过js控制和input标签的方式完成这一效果,无需加载其他组件。具体实例大家大家参考下本文
    2018-05-05
  • 详解Vue 单文件组件的三种写法

    详解Vue 单文件组件的三种写法

    这篇文章主要介绍了详解Vue 单文件组件的三种写法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-02-02

最新评论