websocket demo,websocket封装,jquery下的websocket封装

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/aSuncat/article/details/82744787

一、websocket封装github地址:https://github.com/yquanmei/websocket-demo
二、需求
最近公司要求加入websocket的页面有点多,每次都重复写websocket代码太累,所以就简单封装一下。
这里写图片描述
三、websocket.js
1、需要的参数:
(1)websocket链接每次都需要外部传入,公司链接是ip+url组成,所以就分成了2个部分。
(2)点击某个按钮后,需要断开websocket,所以就是否断开的参数。
(3)onopen、onmessage时的信息交流,需要发送消息,和接收消息,或进行其他操作,所以有对应的3个方法。
(4)因为有时候websocket断了,但是没有进行信息的联通,浏览器端不知道断了,就需要进行心跳检测。如果不需要心跳检测,也可以传入参数heartBeat: false

/*
 * @param {boolean} cancelSocket:是否断开websocket,默认false
 * @param {str} socketIp: websocket的ip,默认后台调取
 * @param {str} wsUrl: websocket的链接,无默认值
 * @param {str} sockUrl: 不支持websocket时的链接,无默认值
 * @param {func} openSendMsg: 打开websocket的onopen时执行的方法
 * @param {func} sendMsg: 连接上后,onmessage中发送消息的方法,无默认值
 * @param {func} receiveMsg: 连接上后,onmessage中接收到消息的方法,无默认值
 * @param {boolean} heartBeat:是否打开心跳检测,默认true
 * @param {num} timeout: 心跳检测的间隔时间,默认10分钟
 */

2、主要方法:initEventHandle中的onopen、onmessage、onclose、onerror方法,具体操作由外部传入

ws.onclose = function () {
      if (getConnect == 1) {
        originThis.reconnect(wsUrl, sockUrl);
        console.log('close():断开');
      }
    };
    ws.onerror = function () {
      if (getConnect == 1) {
        originThis.reconnect(wsUrl, sockUrl);
        console.log('error():报错');
      }
    };
    ws.onopen = function () {
      if (originThis.opts.heartBeat) {
        heartCheckObj.reset().start(); // 心跳检测重置
      }
      if (ws.readyState == 1) {
        var msg = originThis.opts.openSendMsg();
        if (!msg) {
          var openTimeSpe = curTime();
          console.log('onopen():连接成功,' + openTimeSpe);
          msg = '打开时间:' + openTimeSpe;
        }
        ws.send(msg);
        // ws.send('打开时间:' + openTimeSpe);
      }
    };
    ws.onmessage = function (event) {
      if (originThis.opts.heartBeat) {
        heartCheckObj.reset().start(); // 拿到任何消息都说明当前连接是正常的
      }
      originThis.opts.sendMsg && originThis.opts.sendMsg(ws); // 发送消息
      originThis.opts.receiveMsg && originThis.opts.receiveMsg(event); //接收消息
    }

四、websocket.html
1、echo.websocket.org/可以用来测试,只要发送消息,这个网站就会返回发送过去的消息。

  $.newSocket({
    socketIp: 'echo.websocket.org/',
    wsUrl: '',
    sockUrl: null,
    openSendMsg: openSendMsg,
    sendMsg: sendMsg,
    receiveMsg: receiveMsg,
    timeout: 10000
  });

2、如果是取消连接,则直接传入cancelSocket:false就行

 $.newSocket({
      cancelSocket: true
    });

四、代码:https://github.com/yquanmei/websocket-demo

猜你喜欢

转载自blog.csdn.net/aSuncat/article/details/82744787
今日推荐