websocket自动断开重连
Posted timelessmemoryli
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了websocket自动断开重连相关的知识,希望对你有一定的参考价值。
监听close进行重连
<!DOCTYPE html>
<html>
<head>
<title>WebSocket</title>
<script src="jquery.min.js"></script>
<script src="ws.js"></script>
</head>
<body>
<button id="close">close</button>
</body>
</html>
var accessToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIgJI";
var globalwebsocket = null;
$(function()
if ('WebSocket' in window)
websocketLifePeriod();
else
alert("unsupported websocket");
$("#close").click(function()
closeWebSocket();
)
)
function websocketLifePeriod()
var websocket = new WebSocket("ws://7k586s.natappfree.cc:80/yiliao/websocketServer/" + accessToken);
globalwebsocket = websocket;
websocket.onopen = function(event)
alert("success");
sendMsg(
accessToken : accessToken
);
;
websocket.onclose = function(e)
console.log('websocket closed: ' + e.code + ' ' + e.reason + ' ' + e.wasClean)
// if (e.code == 1006)
websocketLifePeriod();
//
alert("closed");
;
websocket.onmessage = function(event)
console.log(event.data);
;
websocket.onerror = function()
alert("error");
;
window.onbeforeunload = function ()
closeWebSocket();
;
function closeWebSocket()
globalwebsocket.close();
function sendMsg(msg)
var data = JSON.stringify(msg);
globalwebsocket.send(data);
以上是关于websocket自动断开重连的主要内容,如果未能解决你的问题,请参考以下文章