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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • kafka删除topic 被标记为删除_kafka支持多少个topic

    kafka删除topic 被标记为删除_kafka支持多少个topic kafka删除topic时的隐患 生产上kafka集群长时间使用会导致topic容器下已被消费的消息过多,进而导致在重新选主时切换时间长的问题。追根到底来讲切换Leader时间都花费在zookeeper文件同步上,但是kafka恰恰没有清理已被消费消息的机制,故导致死尸消息每次在节点重启或者切主都会时间很常,而zookeeper提供了java…

    2022年10月10日
    1
  • 面试又挂了:大厂面试到底更看重学历还是技术?来看看大佬的说法

    面试又挂了:大厂面试到底更看重学历还是技术?来看看大佬的说法前言我是一个普通本科出身的Android程序员,我的学校也不过就是一个普通二本。嗯,我的学弟学妹们也是一样的,都是普通二本。但是和我不同的是,现在的社会越来越浮躁了,浮躁的让人沉不下心认真做事,让人忍不住去想各种有的没的。比如我的这些学弟学妹们。我已经不止一次收到来自他们的私信了,他们问的内容,无一不是表达对自己学历的自卑和对即将离开学校的自己的不自信,还有对面试被拒的伤心。千篇一律的问题,基本内容如下:面试挂了,大厂面试到底更看重学历还是技术?我这样的学历在求职中有什么需要注意点的点吗?

    2022年6月6日
    55
  • 简述pki的体系结构_如何整理知识点

    简述pki的体系结构_如何整理知识点 

    2022年8月22日
    8
  • 我用Python采集了班花的空间数据集,除了美照竟然再一次发现了她另外的秘密![通俗易懂]

    大家好,我是辣条。室友知道了我上次给班花修过电脑,追了我三条街,嘴里大骂我不当人子,怪我这种事情没带他。最后又舔着脸求我支招,这货竟然想追班花!辣条我为了兄弟两(收)肋(钱)插(办)刀(事),毫不犹豫的答应了。但是我只有班花的QQ和微信怎么办呢,那就从她平时发的动态着手,于是就有了这篇文章,不过最后我又发现了她的另一秘密!采集数据目标网址:QQ空间工具使用开发环境:win10、python3.7开发工具:pycharm、Chrome工具包:selenium,re,time.

    2022年4月13日
    39
  • idea创建java项目的步骤_Java为什么新建不了项目

    idea创建java项目的步骤_Java为什么新建不了项目开发工具与关键技术:IDEA与创建项目作者:李哲定撰写时间:2021年5月18日IntelliJIDEA如何创建一个普通的java项目,及创建java文件并运行首先,确保idea软件正确安装完成,java开发工具包jdk安装完成。IntelliJIDEA下载地址:https://www.jetbrains.com/idea/download/#section=windowsjdk下载地址:http://www.oracle.com/technetwork/java/javase/down

    2022年9月30日
    2
  • Vmware安装Ubuntu16.4、Ubuntu里安装python3.9、Ubuntu安装PyCharm的过程及出现的问题的解决[通俗易懂]

    Vmware安装Ubuntu16.4、Ubuntu里安装python3.9、Ubuntu安装PyCharm的过程及出现的问题的解决[通俗易懂]目录1、VMware安装Ubuntu16.4虚拟机1.1、下载Ubuntu镜像文件1.2、安装Ubuntu虚拟机1.2、装Ubuntu系统和虚拟机工具1.3、解决Ubuntu不能全屏显示1.4、设置共享文件夹1.4.1、主机上的文件夹设置1.4.2、虚拟机上的设置1.5、解决/mnt下没有hgfs文件夹1.6、解决找不到共享文件夹的问题1.7、解决重启后共享文件夹没有了的问题2、Ubuntu安装Python3.92.1、安装Python3.92.

    2022年8月29日
    5

发表回复

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

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