// MIT License:
//
// Copyright (c) 2010-2012, Joe Walnes
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

/**
 * This behaves like a WebSocket in every way, except if it fails to connect,
 * or it gets disconnected, it will repeatedly poll until it succesfully connects
 * again.
 *
 * It is API compatible, so when you have:
 *   ws = new WebSocket('ws://....');
 * you can replace with:
 *   ws = new ReconnectingWebSocket('ws://....');
 *
 * The event stream will typically look like:
 *  onconnecting
 *  onopen
 *  onmessage
 *  onmessage
 *  onclose // lost connection
 *  onconnecting
 *  onopen  // sometime later...
 *  onmessage
 *  onmessage
 *  etc...
 *
 * It is API compatible with the standard WebSocket API.
 *
 * Latest version: https://github.com/joewalnes/reconnecting-websocket/
 * - Joe Walnes
 */
(function (global, factory) {

    if (typeof define === 'function' && define.amd) {

        define([], factory);

} else if (typeof module !== 'undefined' && module.exports){

        module.exports = factory();

} else {

        global.ReconnectingWebSocket = factory();

}

})(this, function () {

    function ReconnectingWebSocket(url, protocols) {

        protocols = protocols || [];

        // These can be altered by calling code.
        this.debug = false;
        ;
        this.reconnectDecay = 1.5;
        ;
        ;

        var self = this;
        var ws;
        var forcedClose = false;
        var timedOut = false;

        this.url = url;
        this.protocols = protocols;
        this.readyState = WebSocket.CONNECTING;
        this.URL = url; // Public API

        this.onopen = function(event) {

};

        this.onclose = function(event) {

};

        this.onconnecting = function(event) {

};

        this.onmessage = function(event) {

};

        this.onerror = function(event) {

};

        function connect(reconnectAttempt) {

            ws = new WebSocket(url, protocols);

            self.onconnecting();
            if (self.debug || ReconnectingWebSocket.debugAll) {

                console.debug('ReconnectingWebSocket', 'attempt-connect', url);

}

            var localWs = ws;
            var timeout = setTimeout(function() {

                if (self.debug || ReconnectingWebSocket.debugAll) {

                    console.debug('ReconnectingWebSocket', 'connection-timeout', url);

}
                timedOut = true;
                localWs.close();
                timedOut = false;

}, self.timeoutInterval);

            ws.onopen = function(event) {

                clearTimeout(timeout);
                if (self.debug || ReconnectingWebSocket.debugAll) {

                    console.debug('ReconnectingWebSocket', 'onopen', url);

}
                self.readyState = WebSocket.OPEN;
                reconnectAttempt = false;
                self.reconnectAttempts = ;
                self.onopen(event);

};

            ws.onclose = function(event) {

                clearTimeout(timeout);
                ws = null;
                if (forcedClose) {

                    self.readyState = WebSocket.CLOSED;
                    self.onclose(event);

} else {

                    self.readyState = WebSocket.CONNECTING;
                    self.onconnecting();
                    if (!reconnectAttempt && !timedOut) {

                        if (self.debug || ReconnectingWebSocket.debugAll) {

                            console.debug('ReconnectingWebSocket', 'onclose', url);

}
                        self.onclose(event);

}
                    setTimeout(function() {

                        self.reconnectAttempts++;
                        connect(true);

}, self.reconnectInterval * Math.pow(self.reconnectDecay, self.reconnectAttempts));

}

};
            ws.onmessage = function(event) {

                if (self.debug || ReconnectingWebSocket.debugAll) {

                    console.debug('ReconnectingWebSocket', 'onmessage', url, event.data);

}
                self.onmessage(event);

};
            ws.onerror = function(event) {

                if (self.debug || ReconnectingWebSocket.debugAll) {

                    console.debug('ReconnectingWebSocket', 'onerror', url, event);

}
                self.onerror(event);

};

}
        connect(false);

        this.send = function(data) {

            if (ws) {

                if (self.debug || ReconnectingWebSocket.debugAll) {

                    console.debug('ReconnectingWebSocket', 'send', url, data);

}
                return ws.send(data);

} else {

                throw 'INVALID_STATE_ERR : Pausing to reconnect websocket';

}

};

        this.close = function() {

            forcedClose = true;
            if (ws) {

                ws.close();

}

};

        /**
         * 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();

}

};

}

    /**
     * Setting this to true is the equivalent of setting all instances of ReconnectingWebSocket.debug to true.
     */
    ReconnectingWebSocket.debugAll = false;

    return ReconnectingWebSocket;

});

reconnectingwebsocket.js的更多相关文章

  1. WebSocket重连reconnecting-websocket.js的使用

    原文:https://www.cnblogs.com/kennyliu/p/6477746.html   页面引用 <script src="~/Scripts/reconnectin ...

  2. reconnecting-websocket.js

    websocket是HTML5下一个不错的网络协议解决方案,有一个场景很多猿猿都会遇到,手机锁屏后大约60秒,IOS会自动断开websocket连接,连接丢失了,那我们的数据也就断了.websocke ...

  3. JS中使用reconnecting-websocket实现websocket断开自动重新连接

    这里用了第三方的js 官方地址:https://github.com/joewalnes/reconnecting-websocket 引入js reconnecting-websocket.min. ...

  4. spring WebSocket详解

    场景 websocket是Html5新增加特性之一,目的是浏览器与服务端建立全双工的通信方式,解决http请求-响应带来过多的资源消耗,同时对特殊场景应用提供了全新的实现方式,比如聊天.股票交易.游戏 ...

  5. websocket 重连解决方案

    1.websocket 重连的脚本:https://github.com/joewalnes/reconnecting-websocket                 reconnecting-w ...

  6. WebSocket重连实现

    方式一.使用第三方库实现 比如:reconnecting-websocket.jsReconnectingWebSocket,代码:https://github.com/joewalnes/recon ...

  7. websocket在springboot+vue中的使用

    1.websocket在springboot中的一种实现 在java后台中,websocket是作为一种服务端配置,其配置如下 @Configuration public class WebSocke ...

  8. Vue.js 和 MVVM 小细节

    MVVM 是Model-View-ViewModel 的缩写,它是一种基于前端开发的架构模式,其核心是提供对View 和 ViewModel 的双向数据绑定,这使得ViewModel 的状态改变可以自 ...

  9. js学习笔记:操作iframe

    iframe可以说是比较老得话题了,而且网上也基本上在说少用iframe,其原因大致为:堵塞页面加载.安全问题.兼容性问题.搜索引擎抓取不到等等,不过相对于这些缺点,iframe的优点更牛,跨域请求. ...

随机推荐

  1. 存储过程 Row_number() 分页

    ---恢复内容开始--- 自己之前一直是使用的通用的存储过程 ,也是封装好的只要传表名 + 条件 等等 来到新环境 让自己写一个存储过程, 没办法 自己就需要写一个咯 之前写的比较多的是 按 top ...

  2. LL(1)文法

    <源程序>→<外部声明>|<外部声明><函数体> <外部申明>→<头文件><函数声明>|其他声明 <函数体&g ...

  3. gloolooer

    V1.2gloolooer金[http://sh.yun.ftn.qq.com/ftn_handler/0a9043ee7aa120d3c864281211dff2f08efe5e2d42438ec5 ...

  4. 技术杂记-改造具有监控功能的数据库连接池阿里Druid,支持simple-jndi,kettle

    kettle内置的jndi管理是simple-jndi,功能确实比较简单,我需要监控kettle性能,druid确实是很不错的选择,但没有提供对应的支持,我改进了druid源码,实现了simple-j ...

  5. PHP 版本判断 version_compare() 函数

    在度娘中简单的找了下,判断当前PHP的版本是否高于某个版本,或者低于某个版本的方法 显示的结果基本上都是一样的,好吧,要不是我忘记了version_compare()这个函数我才不会去找度娘,果断找以 ...

  6. 如何设置Vimrc

    .title { text-align: center } .todo { font-family: monospace; color: red } .done { color: green } .t ...

  7. 关闭电脑SSD的磁盘碎片整理

    小白往往会把机械硬盘时代的习惯带进固态硬盘时代,比如碎片整理.机械硬盘时代砖家最喜欢告诉小白:“系统慢了吧?赶紧碎片整理撒.”小白屁颠屁颠地整理去了.殊不知碎片整理对于SSD来说完全就是种折磨.这种“ ...

  8. 第三十二篇:在SOUI2.0中像android一样使用资源

    SOUI2.0之前,在SOUI中使用资源通常是直接使用这个资源的name(一个字符串)来引用.使用字符串的好处在于字符串能够表达这个资源的意义,因此使用字符串也是现代UI引擎常用的方式. 尽管直接使用 ...

  9. LinkedList源码阅读笔记(基于JDK1.8)

    LinkedList是List接口的一个有序链表实现,存储节点是内部类Node,Node中有两个属性prev和next,负责连接前后两个元素.由于不是使用数组进行存储,所以查询需要遍历链表一半的元素( ...

  10. Asp.net中延长session失效时间(2点注意web.config和IIS)

    一个是软件系统中的web.config:   配置文件web.config 的<system.web>下加上<sessionState mode="InProc" ...