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


相关推荐

  • laravel throttle 中间件「建议收藏」

    laravel throttle 中间件

    2022年2月15日
    54
  • 怎样使用父组件向子组件传值【 必看】

    怎样使用父组件向子组件传值【 必看】呃呃,首先小仙女初学Vue传值的时候,是费尽了脑汁,不知道怎么回事。终于,功夫不负有心人,把他弄明白了,如有错误,请多指教!!首先在学习Vue的框架开发的项目过程中,会经常会用到组件来管理不同的功能,有些公共的东西会就会被抽取出来,当做组件去使用。这时必然会产生一些疑问和需求?比如一个组件调用另一个组件作为自己的子组件,那么我们如何进行给子组件进行传值呢?就先和小编一起探究一下吧!父向子传递…

    2022年5月4日
    81
  • 报告上集 | 《认文识字·中文字信息精准化》报告「建议收藏」

    您好,欢迎关注《认文识字——中文字信息精准化》报告。我是安秀。这里说的“中文字”,是“中国文字”的简称,也就是我们常说的“汉字”。【认文识字】是以“中文字信息精准化”为导向,而沉淀出的一整个“从文到字”脉络关系大网和相应的信息数据。今天发表出来,跟您分享。壹○中文字信息精准化研究与分享中文字,是人类文明进程的全息存储;同时,也是人类智能的载体之一。它以多维多元的编码方式,将人脑多维智力运行过程、全息呈现。使用【认文识字】的信息数据,可以在包括人工智能领域的各行各业各领域中,做

    2022年4月7日
    45
  • c语言列车调度,列车调度

    c语言列车调度,列车调度火车站的列车调度铁轨的结构如下图所示:两端分别是一条入口(Entrance)轨道和一条出口(Exit)轨道,它们之间有N条平行的轨道。每趟列车从入口可以选择任意一条轨道进入,最后从出口离开。在图中有9趟列车,在入口处按照{8,4,2,5,3,9,1,6,7}的顺序排队等待进入(一条轨道可以停放多个火车)。如果要求它们必须按序号递减的顺序从出口离开,则至少需要多少条平行铁轨用于调度?输入格式输入第一…

    2022年7月26日
    10
  • 阿里云大数据存储密集型实例d2s云服务器配置性能详解

    阿里云大数据存储密集型实例d2s云服务器配置性能详解阿里云大数据存储密集型实例d2s云服务器配置性能CPU、内存、适用场景、大数据存储密集型d2s实例规格族和优惠报价信息,InstanceTypes分享大数据存储密集型d2s实例详解:大数据存储密集型d2s实例规格族特性I/O优化实例支持ESSD云盘、SSD云盘和高效云盘实例配备大容量、高吞吐SATAHDD本地盘,辅以最大35Gbit/s实例间网络带宽支持在线更换坏盘,支持热插拔坏盘,避免导致实例停机处理器:2.5GHz主频的Intel®Xeon®Platinum8163(Sky.

    2022年5月2日
    59
  • 好用的pycharm插件_pycharm插件推荐

    好用的pycharm插件_pycharm插件推荐软硬件环境windows1064bitpycharm2020.1.2前言可能很多人在使用pycharm的时候压根就没有安装过插件,毕竟pycharm已经足够强大了。但是,这并不妨碍…

    2022年8月26日
    7

发表回复

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

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