webSock 重連機構 簡略版

來源:互聯網
上載者:User

標籤:else   etc   關閉   網路   var   idt   false   off   location   

在頁面載入前 匯入兩個js; 
var socketStatus=false;  var t2;//重連 機構 function tanchuang(){ Offline.check(); //為false 時執行 if(!socketStatus){ AlertSvc.layAlerterr("當前網路不佳,請稍後再試!"); if(Offline.state === ‘up‘ && websocket.reconnectAttempts>websocket.maxReconnectInterval){ window.location.reload(); } } } //websock串連事件 function websocketConnect(add) { if (add === undefined) { add = cip; } if (‘WebSocket‘ in window) { websocket = new ReconnectingWebSocket(add); } else if (‘MozWebSocket‘ in window) { websocket = new MozWebSocket(add); } else { websocket = new SockJS(add); } //串連成功建立的回調方法 websocket.onopen = function() { //重連 機構 socketStatus=true; t2=setInterval(tanchuang,3000); }; //接收到訊息的回調方法 websocket.onmessage = function(event) { }; //串連發生錯誤的回調方法\ websocket.onerror = function() { socketStatus=false; console.log("WebSocket串連錯誤"); }; //串連關閉的回調方法2017-08-15 websocket.onclose = function() { socketStatus=false; console.log("WebSocket串連關閉"); }; //監聽視窗關閉事件,當視窗關閉時,主動去關閉websocket串連,防止串連還沒斷開就關閉視窗,server端會拋異常。 window.onbeforeunload = function() { if(event.clientX > document.body.clientWidth && event.clientY < 0 || event.altKey) { closeWebSocket(); } };
<script src="lib/offline.js"></script>
<script src="lib/reWebsocket.js"></script>
2017-08-15 12:11:29

webSock 重連機構 簡略版

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.