前端websockt可重连功能的插件
詳情參考:
https://www.cnblogs.com/HendSame-JMZ/p/6383443.html
下載兩個包后,直接引入html:
https://github.com/tangcc8/reconnecting-websocket
https://github.com/tangcc8/offline
效果:
最終的效果是:當網絡斷開連接后,會先重連3000次,如果3000次重連不上則瀏覽器放棄重連,開始監聽網絡狀態,如果網絡一恢復,則直接刷新頁面,恢復數據正常。
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;
};
這是實踐代碼(增加了心跳給后臺做判斷前臺是否還在連接中):
<script> var interval; var wsUri ="ws://192.168.1.107/webSocket/9999"; var socket = new ReconnectingWebSocket(wsUri); socket.debug = true;//開啟高度模式 socket.timeoutInterval = 5400;//重連間隔 socket.onmessage = function (message) {// 處理服務器推送過來的數據 console.log(message); }; socket.onopen = function () {//鏈接打開 console.log("Connected to notification socket"); interval=setInterval(function () {var send_data={type:'beat'}; var str=JSON.stringify(send_data); socket.send(str); },5000); } socket.onclose = function () {//鏈接關閉 clearInterval(interval); console.log("Disconnected to notification socket"); }</script>
總結
以上是生活随笔為你收集整理的前端websockt可重连功能的插件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android 仿微信群聊头像 合成图片
- 下一篇: 电脑无法连接mysql_本地电脑无法连接