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

// 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 successfully 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, apart from the following members:
*
* - `bufferedAmount`
* - `extensions`
* - `binaryType`
*
* Latest version: https://github.com/joewalnes/reconnecting-websocket/
* - Joe Walnes
*
* Syntax
* ======
* var socket = new ReconnectingWebSocket(url, protocols, options);
*
* Parameters
* ==========
* url - The url you are connecting to.
* protocols - Optional string or array of protocols.
* options - See below
*
* Options
* =======
* Options can either be passed upon instantiation or set after instantiation:
*
* var socket = new ReconnectingWebSocket(url, null, { debug: true, reconnectInterval: 4000 });
*
* or
*
* var socket = new ReconnectingWebSocket(url);
* socket.debug = true;
* socket.reconnectInterval = 4000;
*
* debug
* - Whether this instance should log debug messages. Accepts true or false. Default: false.
*
* automaticOpen
* - Whether or not the websocket should attempt to connect immediately upon instantiation. The socket can be manually opened or closed at any time using ws.open() and ws.close().
*
* reconnectInterval
* - The number of milliseconds to delay before attempting to reconnect. Accepts integer. Default: 1000.
*
* maxReconnectInterval
* - The maximum number of milliseconds to delay a reconnection attempt. Accepts integer. Default: 30000.
*
* reconnectDecay
* - The rate of increase of the reconnect delay. Allows reconnect attempts to back off when problems persist. Accepts integer or float. Default: 1.5.
*
* timeoutInterval
* - The maximum time in milliseconds to wait for a connection to succeed before closing and retrying. Accepts integer. Default: 2000.
*
*/
(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 () { if (!('WebSocket' in window)) {
return;
} function ReconnectingWebSocket(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'
}
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) {
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 || ReconnectingWebSocket.debugAll) {
console.debug('ReconnectingWebSocket', 'attempt-connect', self.url);
} var localWs = ws;
var timeout = setTimeout(function() {
if (self.debug || ReconnectingWebSocket.debugAll) {
console.debug('ReconnectingWebSocket', 'connection-timeout', self.url);
}
timedOut = true;
localWs.close();
timedOut = false;
}, self.timeoutInterval); ws.onopen = function(event) {
clearTimeout(timeout);
if (self.debug || ReconnectingWebSocket.debugAll) {
console.debug('ReconnectingWebSocket', '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 || ReconnectingWebSocket.debugAll) {
console.debug('ReconnectingWebSocket', '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 || ReconnectingWebSocket.debugAll) {
console.debug('ReconnectingWebSocket', 'onmessage', self.url, event.data);
}
var e = generateEvent('message');
e.data = event.data;
eventTarget.dispatchEvent(e);
};
ws.onerror = function(event) {
if (self.debug || ReconnectingWebSocket.debugAll) {
console.debug('ReconnectingWebSocket', 'onerror', self.url, event);
}
eventTarget.dispatchEvent(generateEvent('error'));
};
} // Whether or not to create a websocket upon instantiation
if (this.automaticOpen == true) {
this.open(false);
} /**
* Transmits data to the server over the WebSocket connection.
*
* @param data a text string, ArrayBuffer or Blob to send to the server.
*/
this.send = function(data) {
if (ws) {
if (self.debug || ReconnectingWebSocket.debugAll) {
console.debug('ReconnectingWebSocket', '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.
*/
ReconnectingWebSocket.prototype.onopen = function(event) {};
/** An event listener to be called when the WebSocket connection's readyState changes to CLOSED. */
ReconnectingWebSocket.prototype.onclose = function(event) {};
/** An event listener to be called when a connection begins being attempted. */
ReconnectingWebSocket.prototype.onconnecting = function(event) {};
/** An event listener to be called when a message is received from the server. */
ReconnectingWebSocket.prototype.onmessage = function(event) {};
/** An event listener to be called when an error occurs. */
ReconnectingWebSocket.prototype.onerror = function(event) {}; /**
* Whether all instances of ReconnectingWebSocket should log debug messages.
* Setting this to true is the equivalent of setting all instances of ReconnectingWebSocket.debug to true.
*/
ReconnectingWebSocket.debugAll = false; ReconnectingWebSocket.CONNECTING = WebSocket.CONNECTING;
ReconnectingWebSocket.OPEN = WebSocket.OPEN;
ReconnectingWebSocket.CLOSING = WebSocket.CLOSING;
ReconnectingWebSocket.CLOSED = WebSocket.CLOSED; return ReconnectingWebSocket;
});

2、监听网络状态的脚本:https://github.com/hubspot/offline                        offline.js

/*! offline-js 0.7.18 */
(function() {
var Offline, checkXHR, defaultOptions, extendNative, grab, handlers, init;
extendNative = function(to, from) {
var e, key, results, val;
results = [];
for (key in from.prototype) try {
val = from.prototype[key], null == to[key] && "function" != typeof val ? results.push(to[key] = val) :results.push(void 0);
} catch (_error) {
e = _error;
}
return results;
}, Offline = {}, Offline.options = window.Offline ? window.Offline.options || {} :{},
defaultOptions = {
checks:{
xhr:{
url:function() {
return "/favicon.ico?_=" + new Date().getTime();
},
timeout:5e3,
type:"HEAD"
},
image:{
url:function() {
return "/favicon.ico?_=" + new Date().getTime();
}
},
active:"xhr"
},
checkOnLoad:!1,
interceptRequests:!0,
reconnect:!0,
deDupBody:!1
}, grab = function(obj, key) {
var cur, i, j, len, part, parts;
for (cur = obj, parts = key.split("."), i = j = 0, len = parts.length; len > j && (part = parts[i],
cur = cur[part], "object" == typeof cur); i = ++j) ;
return i === parts.length - 1 ? cur :void 0;
}, Offline.getOption = function(key) {
var ref, val;
return val = null != (ref = grab(Offline.options, key)) ? ref :grab(defaultOptions, key),
"function" == typeof val ? val() :val;
}, "function" == typeof window.addEventListener && window.addEventListener("online", function() {
return setTimeout(Offline.confirmUp, 100);
}, !1), "function" == typeof window.addEventListener && window.addEventListener("offline", function() {
return Offline.confirmDown();
}, !1), Offline.state = "up", Offline.markUp = function() {
return Offline.trigger("confirmed-up"), "up" !== Offline.state ? (Offline.state = "up",
Offline.trigger("up")) :void 0;
}, Offline.markDown = function() {
return Offline.trigger("confirmed-down"), "down" !== Offline.state ? (Offline.state = "down",
Offline.trigger("down")) :void 0;
}, handlers = {}, Offline.on = function(event, handler, ctx) {
var e, events, j, len, results;
if (events = event.split(" "), events.length > 1) {
for (results = [], j = 0, len = events.length; len > j; j++) e = events[j], results.push(Offline.on(e, handler, ctx));
return results;
}
return null == handlers[event] && (handlers[event] = []), handlers[event].push([ ctx, handler ]);
}, Offline.off = function(event, handler) {
var _handler, ctx, i, ref, results;
if (null != handlers[event]) {
if (handler) {
for (i = 0, results = []; i < handlers[event].length; ) ref = handlers[event][i],
ctx = ref[0], _handler = ref[1], _handler === handler ? results.push(handlers[event].splice(i, 1)) :results.push(i++);
return results;
}
return handlers[event] = [];
}
}, Offline.trigger = function(event) {
var ctx, handler, j, len, ref, ref1, results;
if (null != handlers[event]) {
for (ref = handlers[event].slice(0), results = [], j = 0, len = ref.length; len > j; j++) ref1 = ref[j],
ctx = ref1[0], handler = ref1[1], results.push(handler.call(ctx));
return results;
}
}, checkXHR = function(xhr, onUp, onDown) {
var _onerror, _onload, _onreadystatechange, _ontimeout, checkStatus;
return checkStatus = function() {
return xhr.status && xhr.status < 12e3 ? onUp() :onDown();
}, null === xhr.onprogress ? (_onerror = xhr.onerror, xhr.onerror = function() {
return onDown(), "function" == typeof _onerror ? _onerror.apply(null, arguments) :void 0;
}, _ontimeout = xhr.ontimeout, xhr.ontimeout = function() {
return onDown(), "function" == typeof _ontimeout ? _ontimeout.apply(null, arguments) :void 0;
}, _onload = xhr.onload, xhr.onload = function() {
return checkStatus(), "function" == typeof _onload ? _onload.apply(null, arguments) :void 0;
}) :(_onreadystatechange = xhr.onreadystatechange, xhr.onreadystatechange = function() {
return 4 === xhr.readyState ? checkStatus() :0 === xhr.readyState && onDown(), "function" == typeof _onreadystatechange ? _onreadystatechange.apply(null, arguments) :void 0;
});
}, Offline.checks = {}, Offline.checks.xhr = function() {
var e, xhr;
xhr = new XMLHttpRequest(), xhr.offline = !1, xhr.open(Offline.getOption("checks.xhr.type"), Offline.getOption("checks.xhr.url"), !0),
null != xhr.timeout && (xhr.timeout = Offline.getOption("checks.xhr.timeout")),
checkXHR(xhr, Offline.markUp, Offline.markDown);
try {
xhr.send();
} catch (_error) {
e = _error, Offline.markDown();
}
return xhr;
}, Offline.checks.image = function() {
var img;
img = document.createElement("img"), img.onerror = Offline.markDown, img.onload = Offline.markUp,
img.src = Offline.getOption("checks.image.url");
}, Offline.checks.down = Offline.markDown, Offline.checks.up = Offline.markUp, Offline.check = function() {
return Offline.trigger("checking"), Offline.checks[Offline.getOption("checks.active")]();
}, Offline.confirmUp = Offline.confirmDown = Offline.check, Offline.onXHR = function(cb) {
var _XDomainRequest, _XMLHttpRequest, monitorXHR;
return monitorXHR = function(req, flags) {
var _open;
return _open = req.open, req.open = function(type, url, async, user, password) {
return cb({
type:type,
url:url,
async:async,
flags:flags,
user:user,
password:password,
xhr:req
}), _open.apply(req, arguments);
};
}, _XMLHttpRequest = window.XMLHttpRequest, window.XMLHttpRequest = function(flags) {
var _overrideMimeType, _setRequestHeader, req;
return req = new _XMLHttpRequest(flags), monitorXHR(req, flags), _setRequestHeader = req.setRequestHeader,
req.headers = {}, req.setRequestHeader = function(name, value) {
return req.headers[name] = value, _setRequestHeader.call(req, name, value);
}, _overrideMimeType = req.overrideMimeType, req.overrideMimeType = function(type) {
return req.mimeType = type, _overrideMimeType.call(req, type);
}, req;
}, extendNative(window.XMLHttpRequest, _XMLHttpRequest), null != window.XDomainRequest ? (_XDomainRequest = window.XDomainRequest,
window.XDomainRequest = function() {
var req;
return req = new _XDomainRequest(), monitorXHR(req), req;
}, extendNative(window.XDomainRequest, _XDomainRequest)) :void 0;
}, init = function() {
return Offline.getOption("interceptRequests") && Offline.onXHR(function(arg) {
var xhr;
return xhr = arg.xhr, xhr.offline !== !1 ? checkXHR(xhr, Offline.markUp, Offline.confirmDown) :void 0;
}), Offline.getOption("checkOnLoad") ? Offline.check() :void 0;
}, setTimeout(init, 0), window.Offline = Offline;
}).call(this), function() {
var down, next, nope, rc, reset, retryIntv, tick, tryNow, up;
if (!window.Offline) throw new Error("Offline Reconnect brought in without offline.js");
rc = Offline.reconnect = {}, retryIntv = null, reset = function() {
var ref;
return null != rc.state && "inactive" !== rc.state && Offline.trigger("reconnect:stopped"),
rc.state = "inactive", rc.remaining = rc.delay = null != (ref = Offline.getOption("reconnect.initialDelay")) ? ref :3;
}, next = function() {
var delay, ref;
return delay = null != (ref = Offline.getOption("reconnect.delay")) ? ref :Math.min(Math.ceil(1.5 * rc.delay), 3600),
rc.remaining = rc.delay = delay;
}, tick = function() {
return "connecting" !== rc.state ? (rc.remaining -= 1, Offline.trigger("reconnect:tick"),
0 === rc.remaining ? tryNow() :void 0) :void 0;
}, tryNow = function() {
return "waiting" === rc.state ? (Offline.trigger("reconnect:connecting"), rc.state = "connecting",
Offline.check()) :void 0;
}, down = function() {
return Offline.getOption("reconnect") ? (reset(), rc.state = "waiting", Offline.trigger("reconnect:started"),
retryIntv = setInterval(tick, 1e3)) :void 0;
}, up = function() {
return null != retryIntv && clearInterval(retryIntv), reset();
}, nope = function() {
return Offline.getOption("reconnect") && "connecting" === rc.state ? (Offline.trigger("reconnect:failure"),
rc.state = "waiting", next()) :void 0;
}, rc.tryNow = tryNow, reset(), Offline.on("down", down), Offline.on("confirmed-down", nope),
Offline.on("up", up);
}.call(this), function() {
var clear, flush, held, holdRequest, makeRequest, waitingOnConfirm;
if (!window.Offline) throw new Error("Requests module brought in without offline.js");
held = [], waitingOnConfirm = !1, holdRequest = function(req) {
return Offline.getOption("requests") !== !1 ? (Offline.trigger("requests:capture"),
"down" !== Offline.state && (waitingOnConfirm = !0), held.push(req)) :void 0;
}, makeRequest = function(arg) {
var body, name, password, ref, type, url, user, val, xhr;
if (xhr = arg.xhr, url = arg.url, type = arg.type, user = arg.user, password = arg.password,
body = arg.body, Offline.getOption("requests") !== !1) {
xhr.abort(), xhr.open(type, url, !0, user, password), ref = xhr.headers;
for (name in ref) val = ref[name], xhr.setRequestHeader(name, val);
return xhr.mimeType && xhr.overrideMimeType(xhr.mimeType), xhr.send(body);
}
}, clear = function() {
return held = [];
}, flush = function() {
var body, i, key, len, request, requests, url;
if (Offline.getOption("requests") !== !1) {
for (Offline.trigger("requests:flush"), requests = {}, i = 0, len = held.length; len > i; i++) request = held[i],
url = request.url.replace(/(\?|&)_=[0-9]+/, function(match, chr) {
return "?" === chr ? chr :"";
}), Offline.getOption("deDupBody") ? (body = request.body, body = "[object Object]" === body.toString() ? JSON.stringify(body) :body.toString(),
requests[request.type.toUpperCase() + " - " + url + " - " + body] = request) :requests[request.type.toUpperCase() + " - " + url] = request;
for (key in requests) request = requests[key], makeRequest(request);
return clear();
}
}, setTimeout(function() {
return Offline.getOption("requests") !== !1 ? (Offline.on("confirmed-up", function() {
return waitingOnConfirm ? (waitingOnConfirm = !1, clear()) :void 0;
}), Offline.on("up", flush), Offline.on("down", function() {
return waitingOnConfirm = !1;
}), Offline.onXHR(function(request) {
var _onreadystatechange, _send, async, hold, xhr;
return xhr = request.xhr, async = request.async, xhr.offline !== !1 && (hold = function() {
return holdRequest(request);
}, _send = xhr.send, xhr.send = function(body) {
return request.body = body, _send.apply(xhr, arguments);
}, async) ? null === xhr.onprogress ? (xhr.addEventListener("error", hold, !1),
xhr.addEventListener("timeout", hold, !1)) :(_onreadystatechange = xhr.onreadystatechange,
xhr.onreadystatechange = function() {
return 0 === xhr.readyState ? hold() :4 === xhr.readyState && (0 === xhr.status || xhr.status >= 12e3) && hold(),
"function" == typeof _onreadystatechange ? _onreadystatechange.apply(null, arguments) :void 0;
}) :void 0;
}), Offline.requests = {
flush:flush,
clear:clear
}) :void 0;
}, 0);
}.call(this), function() {
var base, e, i, len, ref, simulate, state;
if (!Offline) throw new Error("Offline simulate brought in without offline.js");
for (ref = [ "up", "down" ], i = 0, len = ref.length; len > i; i++) {
state = ref[i];
try {
simulate = document.querySelector("script[data-simulate='" + state + "']") || ("undefined" != typeof localStorage && null !== localStorage ? localStorage.OFFLINE_SIMULATE :void 0) === state;
} catch (_error) {
e = _error, simulate = !1;
}
}
simulate && (null == Offline.options && (Offline.options = {}), null == (base = Offline.options).checks && (base.checks = {}),
Offline.options.checks.active = state);
}.call(this), function() {
var RETRY_TEMPLATE, TEMPLATE, _onreadystatechange, addClass, content, createFromHTML, el, flashClass, flashTimeouts, init, removeClass, render, roundTime;
if (!window.Offline) throw new Error("Offline UI brought in without offline.js");
TEMPLATE = '<div class="offline-ui"><div class="offline-ui-content"></div></div>',
RETRY_TEMPLATE = '<a href class="offline-ui-retry"></a>', createFromHTML = function(html) {
var el;
return el = document.createElement("div"), el.innerHTML = html, el.children[0];
}, el = content = null, addClass = function(name) {
return removeClass(name), el.className += " " + name;
}, removeClass = function(name) {
return el.className = el.className.replace(new RegExp("(^| )" + name.split(" ").join("|") + "( |$)", "gi"), " ");
}, flashTimeouts = {}, flashClass = function(name, time) {
return addClass(name), null != flashTimeouts[name] && clearTimeout(flashTimeouts[name]),
flashTimeouts[name] = setTimeout(function() {
return removeClass(name), delete flashTimeouts[name];
}, 1e3 * time);
}, roundTime = function(sec) {
var mult, unit, units, val;
units = {
day:86400,
hour:3600,
minute:60,
second:1
};
for (unit in units) if (mult = units[unit], sec >= mult) return val = Math.floor(sec / mult),
[ val, unit ];
return [ "now", "" ];
}, render = function() {
var button, handler;
return el = createFromHTML(TEMPLATE), document.body.appendChild(el), null != Offline.reconnect && Offline.getOption("reconnect") && (el.appendChild(createFromHTML(RETRY_TEMPLATE)),
button = el.querySelector(".offline-ui-retry"), handler = function(e) {
return e.preventDefault(), Offline.reconnect.tryNow();
}, null != button.addEventListener ? button.addEventListener("click", handler, !1) :button.attachEvent("click", handler)),
addClass("offline-ui-" + Offline.state), content = el.querySelector(".offline-ui-content");
}, init = function() {
return render(), Offline.on("up", function() {
return removeClass("offline-ui-down"), addClass("offline-ui-up"), flashClass("offline-ui-up-2s", 2),
flashClass("offline-ui-up-5s", 5);
}), Offline.on("down", function() {
return removeClass("offline-ui-up"), addClass("offline-ui-down"), flashClass("offline-ui-down-2s", 2),
flashClass("offline-ui-down-5s", 5);
}), Offline.on("reconnect:connecting", function() {
return addClass("offline-ui-connecting"), removeClass("offline-ui-waiting");
}), Offline.on("reconnect:tick", function() {
var ref, time, unit;
return addClass("offline-ui-waiting"), removeClass("offline-ui-connecting"), ref = roundTime(Offline.reconnect.remaining),
time = ref[0], unit = ref[1], content.setAttribute("data-retry-in-value", time),
content.setAttribute("data-retry-in-unit", unit);
}), Offline.on("reconnect:stopped", function() {
return removeClass("offline-ui-connecting offline-ui-waiting"), content.setAttribute("data-retry-in-value", null),
content.setAttribute("data-retry-in-unit", null);
}), Offline.on("reconnect:failure", function() {
return flashClass("offline-ui-reconnect-failed-2s", 2), flashClass("offline-ui-reconnect-failed-5s", 5);
}), Offline.on("reconnect:success", function() {
return flashClass("offline-ui-reconnect-succeeded-2s", 2), flashClass("offline-ui-reconnect-succeeded-5s", 5);
});
}, "complete" === document.readyState ? init() :null != document.addEventListener ? document.addEventListener("DOMContentLoaded", init, !1) :(_onreadystatechange = document.onreadystatechange,
document.onreadystatechange = function() {
return "complete" === document.readyState && init(), "function" == typeof _onreadystatechange ? _onreadystatechange.apply(null, arguments) :void 0;
});
}.call(this);

3、页面引用:上述脚本

4、JavaScript demo

var socketStatus=false;
function tanchuang(){
Offline.check();
if(!socketStatus){
$('.big_toast div').html('网络连接已断开!');
$('.big_toast').css('left', '45%');
$('.big_toast').fadeIn("fast");
$('.big_toast').fadeOut(2000);
if(Offline.state === 'up' && websocket.reconnectAttempts>websocket.maxReconnectInterval){
window.location.reload();
}
// buildSocket();
}else{
websocket.send("{}");
}
}
var websocket;
buildSocket();
function buildSocket(){
if ('WebSocket' in window) {
websocket = new ReconnectingWebSocket("ws://host/websocket/get/overview");
} else if ('MozWebSocket' in window) {
// websocket = new MozWebSocket("ws://host/websocket/get/all/data/rt");
websocket = new MozWebSocket("ws://host/websocket/get/overview");
} else {
// websocket = new SockJS("http://192.168.1.114/sockjs/websocket/get/all/data/rt");
websocket = new SockJS("http://host/websocket/get/overview"); } }
websocket.onopen = function (evnt) {
socketStatus=true;
clearInterval(t1);//去掉定时器
t2=setInterval(tanchuang,3000);
// tanchuang();
};
websocket.onmessage = function (evnt) {
};
websocket.onerror = function (evnt) {
socketStatus=false;
};
websocket.onclose = function (evnt) {
socketStatus=false;
};

最终的效果是:当网络断开连接后,会先重连3000次,如果3000次重连不上则浏览器放弃重连,开始监听网络状态,如果网络一恢复,则直接刷新页面,恢复数据正常。

博主开源项目:https://github.com/Enast/hummer,走过路过,请点个赞

websocket 重连解决方案的更多相关文章

  1. ABP从入门到精通(6):快速重命名解决方案

    SolutionRenamer SolutionRenamer 是一个解决方案快速重命名工具.经测试重命名一个全新asp.net zero core项目(ABP asp.net zero,.net c ...

  2. Netty 断线重连解决方案

    http://www.spring4all.com/article/889 本篇文章是Netty专题的第七篇,前面六篇文章如下: 高性能NIO框架Netty入门篇 高性能NIO框架Netty-对象传输 ...

  3. WebSocket重连实现

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

  4. Websocket集群解决方案

    最近在项目中在做一个消息推送的功能,比如客户下单之后通知给给对应的客户发送系统通知,这种消息推送需要使用到全双工的websocket推送消息. 所谓的全双工表示客户端和服务端都能向对方发送消息.不使用 ...

  5. 微信小程序开发——点击防重的解决方案

    对于一些涉及后端接口请求的单击事件,不论后端是否做了请求限制,前端还是有必要进行点击防重处理的. 这样既能减少对服务器端的压力,也能有效防止因重复请求而造成一些不可预期的异常. 尤其是接口请求结果处理 ...

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

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

  7. JS重名解决方案

    一个页面如果引用多个JS,或者像ASP.NET MVC,一个视图包含多个子视图,每个子视图有自己的JS,那么变量.函数的重名冲突机会将会大增. 如何解决? 这里有一个方案: 1.用类来封装子页的JS代 ...

  8. VC ADO “ParameterDirectionEnum”:“enum” 类型等 重定义问题 解决方案

    原因分析: 1.在头文件中: #import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace ...

  9. websocket 心跳重连

    websocket 的基本使用: var ws = new WebSocket(url); ws.onclose = function () { //something reconnect(); // ...

随机推荐

  1. HDU3306—Another kind of Fibonacci

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3306 题目意思:一个斐波那契数列的变式,本来是A[n]=A[n-1]+A[n-2],现在变成A[n]= ...

  2. mybatis调用oracle存储过程例子.

    1.MYBATIS方法: <select id="getFlowNum" statementType="CALLABLE"> <![CDATA ...

  3. 隐藏Apache、nginx和PHP的版本号的配置方法

    最近提示说有漏洞,暴露apache.nginx和php的版本号.网上搜了下,整理的方法如下: 首先说apache 在http.conf文件里添加下面两行,默认是没有的 ServerSignature ...

  4. echarts将折线图改为曲线图

    只要在 series中加上属性: smooth: true(true为曲线.flase为直线)

  5. LeetCode_Two Sum

    Given an array of integers, find two numbers such that they add up to a specific target number. The ...

  6. sql server中使用xp_cmdshell

    关键词:sql server开启高级配置,使用Bat,cmdshell 1.sql server中使用xp_cmdshell --允许配置高级选项 GO RECONFIGURE GO . --开启xp ...

  7. Zabbix基本功能使用手册

    Zabbix基本功能使用手册 vim /etc/zabbix/zabbix_agentd.conf 编辑agent配置文件. 指定那些服务器可以来获取数据,可用逗号隔开指定多台服务器. 这个参数表示a ...

  8. python学习笔记(四)random 、json模块

    一.模块简介 Python 模块(Module),是一个 Python 文件,以 .py 结尾,包含了 Python 对象定义和Python语句. 导入模块 import module #导入模块 f ...

  9. 搭建virtualenv

    一.前言 1.什么是virtualenv? 在开发Python应用程序的时候,系统安装的Python3只有一个版本:3.4.所有第三方的包都会被pip安装到Python3的site-packages目 ...

  10. map::erase陷阱

    map::erase函数在不同版本stl中的差异 1. C++98和C++11标准 http://www.cplusplus.com/reference/map/map/erase/ 2. pj st ...