一、地址
二、代码
var ws;
var lockReconnect = false ;
var wsUrl = 'ws:xxx.1.1.1' ;
function createWebSocket ( url) {
try {
ws = new WebSocket ( url) ;
initEventHandle ( ) ;
} catch ( e ) {
reconnect ( url) ;
}
}
function initEventHandle ( ) {
ws. onclose = function ( ) {
reconnect ( wsUrl) ;
} ;
ws. onerror = function ( ) {
reconnect ( wsUrl) ;
} ;
ws. onopen = function ( ) {
heartCheck. reset ( ) . start ( ) ;
} ;
ws. onmessage = function ( event) {
heartCheck. reset ( ) . start ( ) ;
}
}
function reconnect ( url) {
if ( lockReconnect) return ;
lockReconnect = true ;
setTimeout ( function ( ) {
createWebSocket ( url) ;
lockReconnect = false ;
} , 2000 ) ;
}
var heartCheck = {
timeout: 60000 ,
timeoutObj: null ,
reset: function ( ) {
clearTimeout ( this . timeoutObj) ;
return this ;
} ,
start: function ( ) {
this . timeoutObj = setTimeout ( function ( ) {
ws. send ( "HeartBeat" ) ;
} , this . timeout)
}
}
createWebSocket ( wsUrl) ;