websocket

这套websocket直接拿去用,写个独力的js文件

 let wsConnection = {
   $ws: null,
   lockReturn: false,
   timeout: 60 * 1000 * 5,
   timeoutObj: null,
   timeoutNum: null,
   serverTimeoutObj: null,
   //初始化webSocket长连接
   initWebSocket: function (wsurl) {
     this.$ws = new WebSocket(wsurl);//写入地址 这里的地址可以在initWebSocket方法加入参数
     this.$ws.onopen = this.wsOpen;
     this.$ws.onclose = this.wsClose;
     this.$ws.onmessage = this.wsMsg;
     this.$ws.onerror = this.wsError;
   },
   //打开websocket
   wsOpen: function (e) {
     //开始websocket心跳
     wsConnection.startWsHeartbeat();
     console.log('ws success')
   },
   wsClose: function (e) {
     console.log(e, 'ws close')
   },
   wsMsg: function (msg) {
    //每次接收到服务端消息后 重置websocket心跳
     wsConnection.resetHeartbeat();
     //服务端发送来的消息存到vuex
     console.log("服务器发送来的消息",msg)
   },
   wsError: function (err) {
    console.log(err, 'ws error');
     wsConnection.reconnect()
   },
   //重启websocket
   reconnect: function () {
     let _this = this;
     if (_this.lockReturn) {
       return;
     }
     _this.lockReturn = true;
     _this.timeoutNum && clearTimeout(_this.timeoutNum);
     _this.timeoutNum = setTimeout(function () {
       _this.initWebSocket();
       _this.lockReturn = false;
     }, 3000);
   },
   startWsHeartbeat: function () {
     let _this = this;
     _this.timeoutObj && clearTimeout(_this.timeoutObj);
     _this.serverTimeoutObj && clearTimeout(_this.serverTimeoutObj);
     _this.timeoutObj = setInterval(function () {
       //判断websocket当前状态
       if (_this.$ws.readyState != 1) {
         _this.reconnect()
       }
     }, _this.timeout);
   },
   //重置websocket心跳
   resetHeartbeat: function () {
     let _this = this;
     clearTimeout(_this.timeoutObj);
     clearTimeout(_this.serverTimeoutObj);
     _this.startWsHeartbeat()
   }
 };
 
//抛出websocket对象
 export default wsConnection

那里需要引入直接导入使用

import wsConnection from '@/api/web-socket.js'

//在生命周期调用方法
wsConnection.initWebSocket('ws://localhost:8888')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值