1 Introduction
Usually it is automatically disconnected websocket every 90 no operation is necessary to add a heartbeat mechanism to prevent from breaking
2. Experimental procedure
(1) setting a row jsp or html files, adding elemental
(2) js source code, click View
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 // avoid duplication link 2 var lockReconnect = to false ; . 3 // Path . 4 var wsUrl = $ ( "# wsUrl" ) .val (); . 5 the console.log ( "path" + wsUrl); . 6 // WebSocket objects 7 var WS; . 8 // interval . 9 var TT; 10 . 11 IF ( "WebSocket" in window) { 12 is the console.log ( "support WebSocket" ) 13 is } the else { 14 Alert ( "the browser does not support WebSocket") 15 } 16 . 17 // Create ws connector 18 is var createWebSocket = function (wsUrl) { . 19 the try { 20 is // Success 21 is ws = new new a WebSocket (wsUrl); 22 is webSocketInit (); // initialize function webSocket connector 23 is } the catch ( E) { 24 // fails 25 the console.log ( 'the catch' ); 26 is // reconnection 27 // reconnect function 28 webSocketReconnect (wsUrl); 29 } 30 }; 31 // initialization method, after successfully executing 32 var webSocketInit = function () { 33 is // connected close function 34 is ws.onclose = function () { 35 the console.log ( "connection was closed ..." ); 36 webSocketReconnect (wsUrl) // if the connection is closed reconnecting 37 }; 38 // connection error function 39 ws.onerror = function () { 40 the console.log ( "connection error ..." ); 41 is webSocketReconnect ( wsUrl)// If the connection error is reconnectable 42 }; 43 // connection establishment, the transmission information 44 is ws.onopen = function () { 45 var Message1 = { 46 is "type": "the SUB" , 47 "-Service": "Business 1 - first transmission acknowledgment information " 48 }; 49 ws.send (the JSON.stringify (Message1)); // WebSocket service subscription - may have multiple service 50 // message2 {var = 51 is // " type ": "the SUB", 52 is // '-service ":" service 2 " 53 // }; 54 //ws.send (the JSON.stringify (message2)); 55 // heartbeat starts 56 is heartCheck.start (); // after the subscription service starting heartbeat transmission mechanism 57 }; 58 // After successfully receiving the service subscription server push messages actually string 59 ws.onmessage = function (EVT) { 60 the console.log ( 'message received' + evt.data); 61 is $ ( "# span" ) .html (evt.data); 62 is // the JSON.parse the dATA = var (evt.data); 63 is // IF (DATA.service == "service 1") { 64 // the console.log ( "1 receives traffic data"); 65 // // receiving data services 1, and associated logic 66 // } 67 // IF (DATA.service == "service 2") { 68 // the console.log ( "1 receives traffic data"); 69 // data traffic received @ 2, and associated processing logic 70 // } 71 // receiving a push message back, i.e. reset once heartbeat 72 73 is heartCheck.reset (); 74 }; 75 76 }; 77 78 79 var webSocketReconnect = function (URL) { 80 console.log ( "socket disconnection, reconnection attempt is" ); 81 IF (lockReconnect) { 82 return; 83 } 84 lockReconnect = to true ; 85 // will always back on even not connected, set a delay, to avoid too many requests 86 87 // 88 // timer setting trigger s setTimeout clearly, the reason for adding a Timer, for easy to assign a second timer. 89 // That direct clearTImeout (timer) then the timer again that there is no access to the error. 90 // the timer && clearTimeout (timer) then the timer becomes undefined 91 is TT && the clearTimeout (TT); 92 TT = the setTimeout ( function () { 93 createWebSocket (URL); 94 }, 4000 ) 95 }; 96 97 98 // heartbeat so-called beat detector is periodically accesses the server data only once, because the cause is not used for a long time ws automatically disconnected, 99 // generally no operation is disconnected automatically at intervals of 90 seconds open, therefore, carried out within a time interval of data access, can be disconnected to prevent ws, 100 // Pick 30 seconds, within 30 seconds of the countdown is no operation for a visit, the timer is reset with an operation 101 // 102 // packaged as key-value pairs, the object becomes js, with very similar json 103 var heartCheck = { 104 timeout: 30000, // 30 seconds 105 timeoutObj: null , 106 RESET: function () { // receive is successful a push, will reset the heartbeat detection countdown 30 seconds 107 the clearTimeout ( the this .timeoutObj); //The countdown resets 108 the this .start (); 109 }, 110 Start: function () { // Start heartbeat mechanism is provided countdown 30 seconds 111 the this .timeoutObj = the setTimeout ( function () { 112 var Message = { 113 " type ":" t10010 " , 114 "-service ":" run a heartbeat service == "+ new new a Date () 115 }; 1 16 // effect the JSON.stringify () is to convert the JavaScript object to JSON string 117 // while the JSON.parse () may be JSON string to an object. 118 console.log ( "a heartbeat" ); 119 ws.send (the JSON.stringify (Message)); // start heartbeat 120 }, the this .timeout) 121 } 122 // on onopen connection start promptly started, if the within the timing range, onMessage acquired message to the server, 123 // after the countdown resets reset, acquires from the last message from the rear end 30 seconds perform heartbeat detection, not to see broken. 124 }; 125 126 // begin creating webSocket connector 127 createWebSocket (wsUrl); 128 // / 129 function mysend () { 130. var text = $ ( "# text" ) .val (); 131 is the console.log ( "text:" + text); 132 // sends information ws 133 ws.send (text); 134 135 }
(3) test shots.
3. Experience
The so-called beat detector, a data access is carried out from time to time to the server, because the cause is not used for a long time ws automatically disconnected,
generally no operation is automatically disconnected within an interval of 90 seconds, whereby once the data in the time interval access to prevent disconnection can ws,
Pick 30 seconds, no operation is performed within 30 seconds countdown visit, an operation timer is reset