Introduction of the Open SOURCE. Net Communication Framework NETWORKCOMMS framework five heartbeat detection

Source: Internet
Author: User
Tags keep alive

Original Url: Http://www.cnblogs.com/csdev

Networkcomms is a C # language written by TCP/UDP communication framework The author is the British used to charge the current author has open source license is: Apache License v2

Open Source Address Is: Https://github.com/MarcFletcher/NetworkComms.Net

We know that after the TCP connection is established, if there is no heartbeat detection, the connection will be disconnected for a while. The NETWORKCOMMS framework itself has been perfect for heartbeat detection, and we don't have to worry about it when we use it.

The server side of the NETWORKCOMMS communication framework is set to send heartbeat messages less than the client sends a heartbeat message, so the job of sending a heartbeat message is done primarily by the server Side.

If the server side does not send a heartbeat message beyond the regular time, the client will start Sending.

Related Implementation code:

In the Connectionstatic method:

  protected Static voidtriggerconnectionkeepalivethread () {Lock(staticconnectionlocker) {#ifNetfx_coreif(!shutdownworkerthreads && (connectionkeepaliveworker = =NULL||CONNECTIONKEEPALIVEWORKER.ISCOMPLETED)) {connectionkeepaliveworker=NewTask (connectionkeepaliveworker, taskcreationoptions.longrunning);                Connectionkeepaliveworker.start (); }#else                if(!shutdownworkerthreads && (connectionkeepaliveworker = =NULL|| Connectionkeepaliveworker.threadstate = =THREADSTATE.STOPPED)) {connectionkeepaliveworker=NewThread (connectionkeepaliveworker); Connectionkeepaliveworker.name="Connectionkeepaliveworker"; Connectionkeepaliveworker.isbackground=true;                Connectionkeepaliveworker.start (); }#endif            }        }
 Private Static voidconnectionkeepaliveworker () {if(networkcomms.loggingenabled) NetworkComms.Logger.Debug ("Connection Keep Alive Polling thread has started."); DateTime Lastpollcheck=datetime.now;  while(!Shutdownworkerthreads) {                Try                {#ifNET2//We have a short sleep where so, we can exit the thread fairly quickly if We need too                    if(connectionkeepalivepollintervalsecs = =int. MaxValue) Workedthreadsignal.waitone ( the,false); ElseWorkedthreadsignal.waitone ( -,false);#else                    //We have a short sleep where so, we can exit the thread fairly quickly if We need too                    if(connectionkeepalivepollintervalsecs = =int. MaxValue) Workedthreadsignal.waitone ( the); ElseWorkedthreadsignal.waitone ( -);#endif                    //Check for shutdown here                    if(shutdownworkerthreads) break; //Any connections which we had not seen in the last poll interval get tested using a NULL packet                    if(connectionkeepalivepollintervalsecs <int. MaxValue && (datetime.now-lastpollcheck). TotalSeconds > (Double) {connectionkeepalivepollintervalsecs) {allconnectionssendnullpacketkeepaliv                        E (); Lastpollcheck=datetime.now; }                }                Catch(Exception Ex) {logtools.logexception (ex,"Connectionkeepalivepollerror"); }            }        }
  Private Static voidAllconnectionssendnullpacketkeepalive (BOOLreturnimmediately =false)        {            if(networkcomms.loggingenabled) NetworkComms.Logger.Trace ("starting allconnectionssendnullpacketkeepalive"); //Loop through all connections and test the Alive stateList<connection> allconnections =networkcomms.getexistingconnection (applicationlayerprotocolstatus.enabled); intRemainingconnectioncount =allconnections.count; Queueitempriority nullsendpriority=queueitempriority.abovenormal; ManualResetEvent Allconnectionscomplete=NewManualResetEvent (false);  for(inti =0; I < allconnections.count; i++)            {                //We don ' t send null packets to unconnected UDP connectionsUdpconnection asudp = allconnections[i] asudpconnection; if(asudp! =NULL&& Asudp.connectionudpoptions = =Udpoptions.none) {if(interlocked.decrement (refRemainingconnectioncount) = =0) Allconnectionscomplete.set (); Continue; }                Else                {                    intInnerindex =i; NetworkComms.CommsThreadPool.EnqueueItem (nullsendpriority,NewWaitCallback ((obj) =                    {                        Try                        {                            //If The connection is server side we poll preferentially                            if(allconnections[innerindex]! =NULL)                            {                                if(allconnections[innerindex]. Connectioninfo.serverside) {//We Check the last incoming traffic time//in scenarios where the client is sending us lots of data there are no need to poll                                    if((datetime.now-allconnections[innerindex). Connectioninfo.lasttraffictime). TotalSeconds >Connectionkeepalivepollintervalsecs) allconnections[innerindex].                                Sendnullpacket (); }                                Else                                {                                    //If We are a client side we wait up to a additional 3 seconds to do the poll//this means the server would probably beat us                                    if((datetime.now-allconnections[innerindex). Connectioninfo.lasttraffictime). TotalSeconds > Connectionkeepalivepollintervalsecs +1.0+ (NetworkComms.randomGen.NextDouble () *2.0) ) allconnections[innerindex].                                Sendnullpacket (); }                            }                        }                        Catch(Exception) {}finally                        {                            if(interlocked.decrement (refRemainingconnectioncount) = =0) Allconnectionscomplete.set (); }                    }), NULL); }            }            //Max Wait is 1 seconds per connection            if(!returnimmediately && allconnections.count >0)            {#ifNET2if(!allconnectionscomplete.waitone (allconnections.count *2500,false))#else                if(!allconnectionscomplete.waitone (allconnections.count *2500))#endif                    //this timeout should not really happen so we is going to log an error if it does//logtools.logexception (new timeoutexception ("Timeout after" + allConnections.Count.ToString () + "seconds Waiting For null packet sends to FINISH. "+ remainingconnectioncount.tostring () +" connection Waits Remain. This error indicates very high send load or a possible send deadlock. ")," nullpacketkeepalivetimeouterror ");                    if(networkcomms.loggingenabled) NetworkComms.Logger.Warn ("Timeout after"+ allConnections.Count.ToString () +"seconds waiting for null packet sends to FINISH."+ remainingconnectioncount.tostring () +"Connection Waits Remain. This error indicates very high send load or a possible send deadlock."); }        }

Original Url: Http://www.cnblogs.com/csdev

Introduction of the Open SOURCE. Net Communication Framework NETWORKCOMMS framework five heartbeat detection

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.