vue项目中使用webSocket

本文介绍了如何在Vue项目中全局封装并使用WebSocket,包括在组件内部的调用和应用。
摘要由CSDN通过智能技术生成

项目全局封装webSocket

// 引入webScoket包
import SockJs from 'sockjs-client'

// 创建一个socket类并抛出
export default class Socket {
  constructor (param = {}) {
    this.param = param
    this.reconnectCount = 0
    this.socket = null
    this.taskRemindInterval = null
    this.lockReconnect = false
    this.timeout = 12
    this.lastMessageTime = null
  }

  // 连接webScoket
  connection = () => {
    let { socketUrl } = this.param

    this.lastMessageTime = null

    // 检测当前浏览器决定用什么socket
    if ('WebSocket' in window) {
      this.socket = new WebSocket(socketUrl)
    } else {
      this.socket = new SockJs(socketUrl)

      window.onbeforeunload = function () {
        this.socket.close()
      }
    }

    this.socket.onopen = this.onopen
    this.socket.onmessage = this.onmessage
    this.socket.onclose = this.onclose
    this.socket.onerror &#
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值