JavaScript WebSocket heartbeat detection mechanism Introduction

Source: Internet
Author: User

= = = Test code:

==index.html

<! DOCTYPE html>        ABC    </div></body><script Type= "Text/javascript" src= "js/websocket.js" ></script><script src= "Js/client.js" ></script> 

==websocket.js

varLockreconnect =false;//Avoid WS-Duplicate connectionsvarWS =NULL;//determine if the current browser supports WebSocketvarWsurl =NULL;varConfig = {};functionSocketlink (set) {config=set; Wsurl=Config.url; Createwebsocket (Wsurl); //Connect ws}functioncreatewebsocket (URL) {Try {        if(' WebSocket 'inchwindow) {ws=NewWebSocket (URL, ' Echo-protocol '); } Else if(' Mozwebsocket 'inchwindow) {ws=NewMozwebsocket (URL, ' Echo-protocol '); } Else{alert ("Your browser does not support WebSocket")} initeventhandle (); } Catch(e) {reconnect (URL);    Console.log (e); }}functionIniteventhandle () {ws.onclose=function() {reconnect (Wsurl); Console.log ("LLWS connection off!" +NewDate (). toutcstring ());    }; Ws.onerror=function() {reconnect (Wsurl); Console.log ("LLWS connection Error!");    }; Ws.onopen=function() {Heartcheck.reset (). Start ();//Heartbeat Detection ResetConsole.log ("LLWS connection succeeded!" +NewDate (). toutcstring ());    Config.open (WS)}; Ws.onmessage=function(event) {//If you get to the message, heartbeat detection resetsHeartcheck.reset (). Start ();//getting any message indicates that the current connection is normal.config.msg (EVENT.DATA,WS)};}//listen to the window Shutdown event, when the window is closed, actively to close the WebSocket connection, to prevent the connection has not been disconnected and close the window, the server side will throw an exception. Window.onbeforeunload =function() {ws.close ();}functionReconnect (URL) {if(Lockreconnect)return; Lockreconnect=true; SetTimeout (function() {//no connection will be re-connected, set delay to avoid excessive requestscreatewebsocket (URL); Lockreconnect=false; }, 2000);}//Heartbeat DetectionvarHeartcheck ={timeout:10000,//9 minutes, one heartbeat .Timeoutobj:NULL, Servertimeoutobj:NULL, Reset:function() {cleartimeout ( This. Timeoutobj); Cleartimeout ( This. Servertimeoutobj); return  This; }, start:function() {        varSelf = This;  This. Timeoutobj = SetTimeout (function() {            //here sends a heartbeat, back end receives, returns a heartbeat message,            //OnMessage got a return heartbeat, which means the connection is normal.Ws.send ("Ping"); Console.log ("Ping!") Self.servertimeoutobj= SetTimeout (function() {//if it has not been reset for a certain amount of time, it indicates that the backend is actively disconnectedConsole.log ("Try=close") Ws.close (); //Why this code is executed after the Send detection message, because the purpose of this code is to trigger the OnClose method, in order to implement the OnClose inside the re-connect method
So this code is also very important, there is no such method, sometimes sent a timed detection message to the backend, the backend timeout (we set the time), will not automatically trigger the OnClose method. We only have to execute the Ws.close () code, let WS trigger the OnClose method
of the implementation. If you do not have this code, the connection is not disconnected and the latter does not have a normal detection response, then the browser will not automatically timed off (such as Google browser), Google Browser will automatically trigger OnClose
In the case of disconnection, in the case of no disconnection, that is, the back end response is not normal, the browser will not automatically trigger OnClose, so we need to set a timeout to automatically trigger OnClose, which is the code
's role.
}, Self.timeout)}, This. Timeout)}}

What is the purpose of heartbeat detection?

One is to periodically send messages, so that the connection does not time out automatically disconnected, the backend may set a time-out will automatically disconnect, so it is necessary to send a message to the backend, so that the backend server know that the connection is still in the message can not be broken.

and secondly, in order to detect the normal also connected to the situation, to determine whether the back end is normal, if we sent a timed detection to the back end, the back end in accordance with the agreement to send a test message to the front, so that is normal.

But if the backend is not properly issued, we have to set a time-out to reconnect, we put the heavy ligatures in the onclose inside, when the normal connection situation, the timeout failed to respond to the detection message, the browser will not automatically break the trigger OnClose, so we need to manually trigger, That is, write a ws.close () in the timeout to allow WS-Shutdown to trigger the OnClose method for re-connection.

= = Browser will trigger OnClose case is broken off the network, when the normal connection is not disconnected, the browser will not automatically trigger OnClose, so there is a time-out manual trigger OnClose necessary.

Self.servertimeoutobj = SetTimeout (function() {//if it has not been reset for a certain amount of time, it indicates that the backend is actively disconnectedConsole.log ("Try=close") Ws.close (); //Why should this code be executed after the Send detection message, because the purpose of this code is to trigger the OnClose method, in order to implement the OnClose inside the re-connect method            //So this code is also very important, there is no such method, sometimes sent a timed detection message to the backend, the backend timeout (we set the time), will not automatically trigger the OnClose method. We only have to execute the Ws.close () code, let WS trigger the OnClose method             //of the implementation. If you do not have this code, the connection is not disconnected and the latter does not have a normal detection response, then the browser will not automatically timed off (such as Google browser), Google Browser will automatically trigger OnClose            //In the case of disconnection, in the case of no disconnection, that is, the back end response is not normal, the browser will not automatically trigger OnClose, so we need to set a timeout to automatically trigger OnClose, which is the code            //'s role. }, Self.timeout)
function () {        /// Heartbeat detection resets   when open triggers heartbeat detection        new  Date (). toutcstring ());        Config.open (WS)    };     function // If you get to the message, heartbeat detection resets        // getting any message indicates that the current connection is normal  //If the backend has a message, then the initial heartbeat detection will be reset, unless the timeout is not issued, it will trigger OnClose
Then trigger the re-connect
Config.msg (EVENT.DATA,WS) };

==client.js

var number=0; var config = {    ' ws://localhost:8080/',    + =        {function Sendnumber () {            if (ws.readystate = = = ws. OPEN) {                = number+1;                Ws.send (Number.tostring ());                             }        }        Sendnumber ()    },    + =        {"msg")    }}socketlink (config)

==node Back-end test code:

#!/usr/bin/env nodevarWebsocketserver = require (' WebSocket ')). server;varHTTP = require (' http ');varServer = Http.createserver (function(Request, Response) {Console.log (NewDate ()) + ' Received request for ' +Request.url); Response.writehead (404); Response.End ();}); Server.listen (8080,function() {Console.log (NewDate ()) + ' Server is listening on port 8080 ');}); WSServer=NewWebsocketserver ({httpserver:server,//You should don't use autoacceptconnections for production    //applications, as it defeats all standard Cross-origin protection    //facilities built into the protocol and the browser. You should    //*always* Verify the connection ' s origin and decide whether or not    //To accept it.Autoacceptconnections:false});functionOriginisallowed (Origin) {Console.log (Origin,"Origin")    //put logic detect whether the specified origin is allowed.    return true;} Wsserver.on (' Request ',function(Request) {if(!originisallowed (Request.origin)) {        //Make sure we have accept requests from an allowed OriginRequest.reject (); Console.log ((NewDate ()) + ' Connection from Origin ' + Request.origin + ' rejected. '); return; }    varConnection = request.accept (' Echo-protocol '), Request.origin); Console.log ((NewDate ()) + ' Connection accepted. '); Connection.on (' Message ',function(message) {if(Message.type = = = ' UTF8 ')) {Console.log (' Received Message: ' +message.utf8data); //Connection.sendutf (Message.utf8data); Commented out to test how the front end responds without a back end response. }Else if(Message.type = = = ' binary ') {Console.log (' Received Binary Message of ' + message.binaryData.length + ' bytes ');        Connection.sendbytes (Message.binarydata);    }    }); Connection.on (' Close ',function(Reasoncode, description) {Console.log (NewDate ()) + ' Peer ' + connection.remoteaddress + ' disconnected. '); });});

JavaScript WebSocket heartbeat detection mechanism Introduction

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.