WebSocket断线自动重连javascript库(含心跳包)

WebSocket断线自动重连javascript库(含心跳包)ReconnectingWebSocket是一个小型的JavaScript库,封装了WebSocketAPI提供了在连接断开时自动重连的机制。//只需要简单的将:varws=newWebSocket(‘ws://….’);//替换成:varws=newReconnectingWebSocket(‘ws://….’);原ReconnectingWebSocket的GITHUB下载地址下面是我从ReconnectingWebSocket源代码里根据我自身.

大家好,又见面了,我是你们的朋友全栈君。

ReconnectingWebSocket 是一个小型的 JavaScript 库,封装了 WebSocket API
提供了在连接断开时自动重连的机制。

// 只需要简单的将:
var ws = new WebSocket('ws://....');
// 替换成:
var ws = new ReconnectingWebSocket('ws://....');

原ReconnectingWebSocket的GITHUB下载地址
下面是我从ReconnectingWebSocket源代码里根据我自身的业务需求修改的重连库

(function (global, factory) { 
   
    if (typeof define === 'function' && define.amd) { 
   
        define([], factory);
    } else if (typeof module !== 'undefined' && module.exports){ 
   
        module.exports = factory();
    } else { 
   
        global.SlWebSocket = factory();
    }
})(this, function () { 
   

    if (!('WebSocket' in window)) { 
   
        return;
    }

    function SlWebSocket(url, protocols, options) { 
   

        // Default settings
        var settings = { 
   

            /** Whether this instance should log debug messages. */
            debug: false,

            /** Whether or not the websocket should attempt to connect immediately upon instantiation. */
            automaticOpen: true,

            /** The number of milliseconds to delay before attempting to reconnect. */
            reconnectInterval: 1000,
            /** The maximum number of milliseconds to delay a reconnection attempt. */
            maxReconnectInterval: 30000,
            /** The rate of increase of the reconnect delay. Allows reconnect attempts to back off when problems persist. */
            reconnectDecay: 1.5,

            /** The maximum time in milliseconds to wait for a connection to succeed before closing and retrying. */
            timeoutInterval: 2000,

            /** The maximum number of reconnection attempts to make. Unlimited if null. */
            maxReconnectAttempts: null,

            /** The binary type, possible values 'blob' or 'arraybuffer', default 'blob'. */
            binaryType: 'blob',

            /** 心跳包定时器-by slong .*/
            heartbeat_time: null,

            /** 心跳持续时间-by slong .*/
            heartbeat_duration: 30,

            /** 心跳包数据-by slong .*/
            heartbeat_content: ''
        }
        if (!options) { 
    options = { 
   }; }

        // Overwrite and define settings with options if they exist.
        for (var key in settings) { 
   
            if (typeof options[key] !== 'undefined') { 
   
                this[key] = options[key];
            } else { 
   
                this[key] = settings[key];
            }
        }

        // These should be treated as read-only properties

        /** The URL as resolved by the constructor. This is always an absolute URL. Read only. */
        this.url = url;

        /** The number of attempted reconnects since starting, or the last successful connection. Read only. */
        this.reconnectAttempts = 0;

        /** * The current state of the connection. * Can be one of: WebSocket.CONNECTING, WebSocket.OPEN, WebSocket.CLOSING, WebSocket.CLOSED * Read only. */
        this.readyState = WebSocket.CONNECTING;

        /** * A string indicating the name of the sub-protocol the server selected; this will be one of * the strings specified in the protocols parameter when creating the WebSocket object. * Read only. */
        this.protocol = null;

        // Private state variables

        var self = this;
        var ws;
        var forcedClose = false;
        var timedOut = false;
        var eventTarget = document.createElement('div');

        // Wire up "on*" properties as event handlers

        eventTarget.addEventListener('open',       function(event) { 
    self.onopen(event); });
        eventTarget.addEventListener('close',      function(event) { 
    self.onclose(event); });
        eventTarget.addEventListener('connecting', function(event) { 
    self.onconnecting(event); });
        eventTarget.addEventListener('message',    function(event) { 
    self.onmessage(event); });
        eventTarget.addEventListener('error',      function(event) { 
    self.onerror(event); });

        // Expose the API required by EventTarget

        this.addEventListener = eventTarget.addEventListener.bind(eventTarget);
        this.removeEventListener = eventTarget.removeEventListener.bind(eventTarget);
        this.dispatchEvent = eventTarget.dispatchEvent.bind(eventTarget);

        /** * This function generates an event that is compatible with standard * compliant browsers and IE9 - IE11 * * This will prevent the error: * Object doesn't support this action * * http://stackoverflow.com/questions/19345392/why-arent-my-parameters-getting-passed-through-to-a-dispatched-event/19345563#19345563 * @param s String The name that the event should use * @param args Object an optional object that the event will use */
        function generateEvent(s, args) { 
   
            var evt = document.createEvent("CustomEvent");
            evt.initCustomEvent(s, false, false, args);
            return evt;
        };

        this.open = function (reconnectAttempt) { 
   
            let that = this;
            ws = new WebSocket(self.url, protocols || []);
            ws.binaryType = this.binaryType;

            if (reconnectAttempt) { 
   
                if (this.maxReconnectAttempts && this.reconnectAttempts > this.maxReconnectAttempts) { 
   
                    return;
                }
            } else { 
   
                eventTarget.dispatchEvent(generateEvent('connecting'));
                this.reconnectAttempts = 0;
            }

            if (self.debug || SlWebSocket.debugAll) { 
   
                console.debug('SlWebSocket', 'attempt-connect', self.url);
            }

            var localWs = ws;
            var timeout = setTimeout(function() { 
   
                if (self.debug || SlWebSocket.debugAll) { 
   
                    console.debug('SlWebSocket', 'connection-timeout', self.url);
                }
                timedOut = true;
                localWs.close();
                timedOut = false;
            }, self.timeoutInterval);

            ws.onopen = function(event) { 
   
                // that.send();// 触发心跳包,一般接入成功就会进行token等鉴权判断,所以该行可忽略
                clearTimeout(timeout);
                if (self.debug || SlWebSocket.debugAll) { 
   
                    console.debug('SlWebSocket', 'onopen', self.url);
                }
                self.protocol = ws.protocol;
                self.readyState = WebSocket.OPEN;
                self.reconnectAttempts = 0;
                var e = generateEvent('open');
                e.isReconnect = reconnectAttempt;
                reconnectAttempt = false;
                eventTarget.dispatchEvent(e);
            };

            ws.onclose = function(event) { 
   
                clearTimeout(timeout);
                ws = null;
                if (forcedClose) { 
   
                    self.readyState = WebSocket.CLOSED;
                    eventTarget.dispatchEvent(generateEvent('close'));
                } else { 
   
                    self.readyState = WebSocket.CONNECTING;
                    var e = generateEvent('connecting');
                    e.code = event.code;
                    e.reason = event.reason;
                    e.wasClean = event.wasClean;
                    eventTarget.dispatchEvent(e);
                    if (!reconnectAttempt && !timedOut) { 
   
                        if (self.debug || SlWebSocket.debugAll) { 
   
                            console.debug('SlWebSocket', 'onclose', self.url);
                        }
                        eventTarget.dispatchEvent(generateEvent('close'));
                    }

                    var timeout = self.reconnectInterval * Math.pow(self.reconnectDecay, self.reconnectAttempts);
                    setTimeout(function() { 
   
                        self.reconnectAttempts++;
                        self.open(true);
                    }, timeout > self.maxReconnectInterval ? self.maxReconnectInterval : timeout);
                }
            };
            ws.onmessage = function(event) { 
   
                if (self.debug || SlWebSocket.debugAll) { 
   
                    console.debug('SlWebSocket', 'onmessage', self.url, event.data);
                }
                var e = generateEvent('message');
                e.data = event.data;
                eventTarget.dispatchEvent(e);
            };
            ws.onerror = function(event) { 
   
                if (self.debug || SlWebSocket.debugAll) { 
   
                    console.debug('SlWebSocket', 'onerror', self.url, event);
                }
                eventTarget.dispatchEvent(generateEvent('error'));
            };
        }

        // Whether or not to create a websocket upon instantiation
        if (this.automaticOpen == true) { 
   
            this.open(false);
        }

        /** * 改造后的send方法 * * @param data a text string, ArrayBuffer or Blob to send to the server. */
        this.send = function(type,param) { 
   
            if (ws) { 
   
                if (self.debug || SlWebSocket.debugAll) { 
   
                    console.debug('SlWebSocket', 'send', self.url, data);
                }
                clearTimeout(this.heartbeat_time);// 清除上次未执行的心跳
                this.heartbeat_time = setTimeout(this.send.bind(this),this.heartbeat_duration * 1000,'__HEARTBEAT__');
                if(type === '__HEARTBEAT__'){ 
   
                    ws.send(this.heartbeat_content);
                }
                else if(typeof type === 'object'){ 
   
                    ws.send(JSON.stringify(type));
                }
                else if(type && param){ 
   
                    ws.send(JSON.stringify({ 
   type,param}));
                }
            } else { 
   
                throw 'INVALID_STATE_ERR : Pausing to reconnect websocket';
            }
        };

        /** * Transmits data to the server over the WebSocket connection. * * @param data a text string, ArrayBuffer or Blob to send to the server. */
        this.sendRaw = function(data) { 
   
            if (ws) { 
   
                if (self.debug || SlWebSocket.debugAll) { 
   
                    console.debug('SlWebSocket', 'send', self.url, data);
                }
                return ws.send(data);
            } else { 
   
                throw 'INVALID_STATE_ERR : Pausing to reconnect websocket';
            }
        };

        /** * Closes the WebSocket connection or connection attempt, if any. * If the connection is already CLOSED, this method does nothing. */
        this.close = function(code, reason) { 
   
            // Default CLOSE_NORMAL code
            if (typeof code == 'undefined') { 
   
                code = 1000;
            }
            forcedClose = true;
            if (ws) { 
   
                ws.close(code, reason);
            }
        };

        /** * Additional public API method to refresh the connection if still open (close, re-open). * For example, if the app suspects bad data / missed heart beats, it can try to refresh. */
        this.refresh = function() { 
   
            if (ws) { 
   
                ws.close();
            }
        };
    }

    /** * An event listener to be called when the WebSocket connection's readyState changes to OPEN; * this indicates that the connection is ready to send and receive data. */
    SlWebSocket.prototype.onopen = function(event) { 
   };
    /** An event listener to be called when the WebSocket connection's readyState changes to CLOSED. */
    SlWebSocket.prototype.onclose = function(event) { 
   };
    /** An event listener to be called when a connection begins being attempted. */
    SlWebSocket.prototype.onconnecting = function(event) { 
   };
    /** An event listener to be called when a message is received from the server. */
    SlWebSocket.prototype.onmessage = function(event) { 
   };
    /** An event listener to be called when an error occurs. */
    SlWebSocket.prototype.onerror = function(event) { 
   };

    /** * Whether all instances of SlWebSocket should log debug messages. * Setting this to true is the equivalent of setting all instances of SlWebSocket.debug to true. */
    SlWebSocket.debugAll = false;

    SlWebSocket.CONNECTING = WebSocket.CONNECTING;
    SlWebSocket.OPEN = WebSocket.OPEN;
    SlWebSocket.CLOSING = WebSocket.CLOSING;
    SlWebSocket.CLOSED = WebSocket.CLOSED;

    return SlWebSocket;
});

使用时把new new WebSocket(‘ws://…’)替换成new SlWebSocket(‘ws://…’);
下载ReconnectingWebSocket + 修改后的SlWebSocket资源包

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/161192.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 网站被挂马了如何清理_网站在线挂马检测工具

    网站被挂马了如何清理_网站在线挂马检测工具
     
    您好,今天我们讲下挂马的危害和处理办法。挂马是常见的对网站和客户都影响巨大的危害之一。
          上海快网的经验是:如果是在访问出来的源文件的头上,或是最后有被加代码,这个一般是网站文件被要改了,或是ARP,如果是源文件的很多数据位置(中间),那一般是数据库被人挂了。
         不完全统计,90%的网站都被挂过马,挂马是指在获取网站或者网站服务器的部分或者全部权限后,在网页文件中插入一段恶意代码,这些恶意代码主要是一些包括IE等漏洞利用代码,用户访问被挂马

    2022年9月30日
    1
  • pycharm2021激活码(JetBrains全家桶)

    (pycharm2021激活码)本文适用于JetBrains家族所有ide,包括IntelliJidea,phpstorm,webstorm,pycharm,datagrip等。IntelliJ2021最新激活注册码,破解教程可免费永久激活,亲测有效,下面是详细链接哦~https://javaforall.net/100143.html…

    2022年3月27日
    136
  • 1_项目搭建

    1_项目搭建数据库父工程1、建Module:supergo_parent2、改pom<?xmlversion=”1.0″encoding=”UTF-8″?><projectxmlns=”http://maven.apache.org/POM/4.0.0″xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”xsi:schemaLocation=”http://maven.apache.org/POM/4.

    2022年6月25日
    29
  • 优秀的数据工程师,怎么用 Spark 在 TiDB 上做 OLAP 分析[通俗易懂]

    优秀的数据工程师,怎么用 Spark 在 TiDB 上做 OLAP 分析[通俗易懂]优秀的数据工程师,怎么用 Spark 在 TiDB 上做 OLAP 分析

    2022年4月21日
    41
  • matlab norm函数作用_norm值计算

    matlab norm函数作用_norm值计算%X为向量,求欧几里德范数,即。n=norm(X,inf)%求-范数,即。n=norm(X,1)%求1-范数,即。n=norm(X,-inf)%求向量X的元素的绝对值的最小值,即。n=norm(X,p)%求p-范数,即,所以norm(X,2)=norm(X)。命令矩阵的范数函数norm格式n=norm(A)

    2022年10月24日
    0
  • Quartus-II 13 和Modelsim的安装「建议收藏」

    目录一、QuartusII的下载1、下载2、安装三、QuartusII的注册四、安装完成二、ModelsimSE的下载安装与注册一、下载二、安装三、ModelsimSE的注册四、安装完成一、QuartusII的下载1、下载百度网盘下载安装包链接:https://pan.baidu.com/s/1a9d-bq9RZmWrRV542X4IEA提取码:ifte2、安装复制这一串ID三、QuartusII的注册注册器下载:https://pan.baidu.

    2022年4月16日
    59

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号