日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > HTML >内容正文

HTML

前端websockt可重连功能的插件

發布時間:2023/12/14 HTML 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 前端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可重连功能的插件的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。