vue使用websocket

vue使用websocket

前端和后端的交互模式最常见的就是前端发送数据请求,从后端拿到数据后展示到页面中,如果前端不做操作,后端不能主动向前端推送数据,这也是http协议的缺陷。因此,一种新的通信协议应运而生---websocket,他最大的特点就是服务端可以主动向前端推送消息,客户端也可以主动向服务端发送消息,实现了真正的平等,下面封装了websocket,可以直接使用,然后vue.config.js配置websocket代理即可:

      // 代理配置/ws/order根据你自己接口来配置
      '/ws/order': {
        target: 'http://10.10.10.240:7888',
        ws: true,
        secure: false,
        changeOrigin: true
      },

下面写的方法,新建wsMixin.js文件,直接在vue页面混合使用即可

import { default as ReconnectingWebSocket } from '@/assets/js/reconnecting-websocket.min.js'
const wsMixin = {
  data() {
    return {
      websocket: null
    }
  },
  beforeDestroy() {
    // 关闭当前连接
    this.websocket.close()
  },
  methods: {
    initWebSocket(ip, path) {
      const wsUrl = (window.location.protocol === 'https:' ? `wss://${ip}` : `ws://${ip}`) + path
      // this.websocket = new WebSocket(wsUrl)
      // ReconnectingWebSocket断开链接3秒自动连接
      this.websocket= new ReconnectingWebSocket(wsUrl, null, {
        debug: true,
        reconnectInterval: 3000
      })
      this.websocket.onmessage = this.wsOnmessage
      this.websocket.onopen = this.wsOnopen
      this.websocket.onerror = this.wsOnerror
      this.websocket.onclose = this.wsClose
    },
    // 客户端接收到服务端数据的回调
    wsOnmessage(res) {
      const data = JSON.parse(res.data)
    },
    // 连接成功后的回调
    wsOnopen() {
      console.log('连接成功')
    },
    // 连接失败后的回调
    wsOnerror() {},
    // 连接关闭后的回调
    wsClose() {},
    // 向服务器发送数据
    wsSend(data) {
      this.websocket.send(JSON.stringify(data))
    }
  }
}
export default wsMixin

 在src/assets/js/reconnecting-websocket.min.js目录新增JS文件为reconnecting-websocket.min.js如下:

!(function (a, b) {
  'function' == typeof define && define.amd
    ? define([], b)
    : 'undefined' != typeof module && module.exports
    ? (module.exports = b())
    : (a.ReconnectingWebSocket = b())
})(this, function () {
  function a(b, c, d) {
    function l(a, b) {
      var c = document.createEvent('CustomEvent')
      return c.initCustomEvent(a, !1, !1, b), c
    }
    var e = {
      debug: !1,
      automaticOpen: !0,
      reconnectInterval: 1e3,
      maxReconnectInterval: 3e4,
      reconnectDecay: 1.5,
      timeoutInterval: 2e3
    }
    d || (d = {})
    for (var f in e) this[f] = 'undefined' != typeof d[f] ? d[f] : e[f]
    ;(this.url = b), (this.reconnectAttempts = 0), (this.readyState = WebSocket.CONNECTING), (this.protocol = null)
    var h,
      g = this,
      i = !1,
      j = !1,
      k = document.createElement('div')
    k.addEventListener('open', function (a) {
      g.onopen(a)
    }),
      k.addEventListener('close', function (a) {
        g.onclose(a)
      }),
      k.addEventListener('connecting', function (a) {
        g.onconnecting(a)
      }),
      k.addEventListener('message', function (a) {
        g.onmessage(a)
      }),
      k.addEventListener('error', function (a) {
        g.onerror(a)
      }),
      (this.addEventListener = k.addEventListener.bind(k)),
      (this.removeEventListener = k.removeEventListener.bind(k)),
      (this.dispatchEvent = k.dispatchEvent.bind(k)),
      (this.open = function (b) {
        ;(h = new WebSocket(g.url, c || [])),
          b || k.dispatchEvent(l('connecting')),
          (g.debug || a.debugAll) && console.debug('ReconnectingWebSocket', 'attempt-connect', g.url)
        var d = h,
          e = setTimeout(function () {
            ;(g.debug || a.debugAll) && console.debug('ReconnectingWebSocket', 'connection-timeout', g.url),
              (j = !0),
              d.close(),
              (j = !1)
          }, g.timeoutInterval)
        ;(h.onopen = function () {
          clearTimeout(e),
            (g.debug || a.debugAll) && console.debug('ReconnectingWebSocket', 'onopen', g.url),
            (g.protocol = h.protocol),
            (g.readyState = WebSocket.OPEN),
            (g.reconnectAttempts = 0)
          var d = l('open')
          ;(d.isReconnect = b), (b = !1), k.dispatchEvent(d)
        }),
          (h.onclose = function (c) {
            if ((clearTimeout(e), (h = null), i)) (g.readyState = WebSocket.CLOSED), k.dispatchEvent(l('close'))
            else {
              g.readyState = WebSocket.CONNECTING
              var d = l('connecting')
              ;(d.code = c.code),
                (d.reason = c.reason),
                (d.wasClean = c.wasClean),
                k.dispatchEvent(d),
                b ||
                  j ||
                  ((g.debug || a.debugAll) && console.debug('ReconnectingWebSocket', 'onclose', g.url),
                  k.dispatchEvent(l('close')))
              var e = g.reconnectInterval * Math.pow(g.reconnectDecay, g.reconnectAttempts)
              setTimeout(
                function () {
                  g.reconnectAttempts++, g.open(!0)
                },
                e > g.maxReconnectInterval ? g.maxReconnectInterval : e
              )
            }
          }),
          (h.onmessage = function (b) {
            ;(g.debug || a.debugAll) && console.debug('ReconnectingWebSocket', 'onmessage', g.url, b.data)
            var c = l('message')
            ;(c.data = b.data), k.dispatchEvent(c)
          }),
          (h.onerror = function (b) {
            ;(g.debug || a.debugAll) && console.debug('ReconnectingWebSocket', 'onerror', g.url, b),
              k.dispatchEvent(l('error'))
          })
      }),
      1 == this.automaticOpen && this.open(!1),
      (this.send = function (b) {
        if (h) return (g.debug || a.debugAll) && console.debug('ReconnectingWebSocket', 'send', g.url, b), h.send(b)
        throw 'INVALID_STATE_ERR : Pausing to reconnect websocket'
      }),
      (this.close = function (a, b) {
        'undefined' == typeof a && (a = 1e3), (i = !0), h && h.close(a, b)
      }),
      (this.refresh = function () {
        h && h.close()
      })
  }
  return (
    (a.prototype.onopen = function () {}),
    (a.prototype.onclose = function () {}),
    (a.prototype.onconnecting = function () {}),
    (a.prototype.onmessage = function () {}),
    (a.prototype.onerror = function () {}),
    (a.debugAll = !1),
    (a.CONNECTING = WebSocket.CONNECTING),
    (a.OPEN = WebSocket.OPEN),
    (a.CLOSING = WebSocket.CLOSING),
    (a.CLOSED = WebSocket.CLOSED),
    a
  )
})

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值