socket 在VUE封装

在vue中创建js

直接上js代码

/**
 * websocket 工具类
 * @auto maomao
 */
class WebSocketClient{
  /**
   *
   * @param option
   *  {
   *      ip: IP地址
   *      port: 端口
   *      timeout: 心跳时间,单位:毫秒
   *  }
   * @param callback 接收消息的回调
   */
  constructor(option,callback){
    this.ip = option.ip;
    this.callback= callback;/*回调方法*/
    this.uri ="";
    this.ws ={};
    if(typeof option.port == 'number' ){
      this.port = option.port;
    }else{
      this.port = 6000;
    }

    if(typeof option.timeout == 'number' ) {/*单位秒*/
      this.timeout = option.timeout;
    } else {
      this.timeout = 10000;
    }

    this.timeoutObj = null;
    this.serverTimeoutObj = null;
    this.lockReconnect = false;

    this.reconect= null;
    this._createWebSocket();
    if(typeof this.uri =="undefined") {
      this.callback("error");
    }
  }

  _createWebSocket() {
    let me = this;
    this.uri = "ws://" + this.ip + ":" + this.port;
    let ws=new WebSocket(this.uri );//创建websocket连接
    ws.onopen= (evt)=> {//onopen属性,用于指定;连接成功后的回调函数
      this._heartCheckWebSocket();//心跳检测重置
    };
    ws.onmessage = (evt)=> {//onmessage属性 用于指定收到服务器数据后的回调函数
      // console.log("收到的信息:"+evt.data);
      this.callback(evt);
    };

    ws.onclose = (evt)=> {//onclose属性,用于指定连接关闭后的回调函数。
      console.log(me.uri+"【连接关闭】")
      ws.close();//close()方法 关闭WebSocket连接
      this._reconnectWebSocket();
    }

    ws.onerror = (evt)=>{ //实例对象的onerror属性,用于指定报错时的回调函数。
      this._reconnectWebSocket();
      console.error(me.uri+"【连接出错】!");
    };
    this.ws = ws;

  }

  //心跳检测
  _heartCheckWebSocket() {
    if(this.timeoutObj){
      clearInterval(this.timeoutObj);
    }
    let timeout =this.timeout;
    let me = this;
    this.timeoutObj = setInterval(()=> {//开启 这里发送一个心跳,后端收到后,返回一个心跳消息,
      me.ws.send('heartCheck');//onmessage拿到返回的心跳就说明连接正常
    }, timeout);
  }

  //重连
  _reconnectWebSocket() {
    if(this.lockReconnect) return;
    this.lockReconnect = true;
    console.log(this.reconect)
    if(this.reconect){
      clearInterval(this.reconect);
    }
    let me = this;
    this.reconect =setInterval(()=> {//没有连上一直重连
      if(typeof me.uri !="undefined"){
        me._createWebSocket(me.uri);
        me.lockReconnect = false;
      }
    }, 5000);
  }


  /**
   * 发送消息
   * @param msg 消息内容
   */
  sendMessage(msg) {/*发送消息*/
    this.ws.send(msg);
  }
}
export default WebSocketClient;

使用在页面直接引入

import WebSocketClient from '你js的路径'
new WebSocketClient({
    ip:'ip地址',
    port:端口(8080),
    timeout:心跳时长(1000)
  })

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值