介紹開源的.net通訊架構NetworkComms架構之五 心跳檢測

來源:互聯網
上載者:User

標籤:

原文網址: http://www.cnblogs.com/csdev

Networkcomms 是一款C# 語言編寫的TCP/UDP通訊架構  作者是英國人  以前是收費的 目前作者已經開源  許可是:Apache License v2

開源地址是:https://github.com/MarcFletcher/NetworkComms.Net

我們知道TCP串連建立之後,如果沒有心跳檢測,串連一會就斷開了。NetworkComms架構本身已經完美實現了心跳檢測,我們在使用的時候不用再關心這個問題。

NetworkComms通訊架構中伺服器端設定的發送心跳訊息的時間小於用戶端發送心跳訊息,所以發送心跳訊息的工作主要由伺服器端來完成。

如果伺服器端超出常規時間沒有發送心跳訊息,用戶端才會開始發送。

相關實現代碼:

ConnectionStatic方法中:

  protected static void TriggerConnectionKeepAliveThread()        {            lock (staticConnectionLocker)            {#if NETFX_CORE                if (!shutdownWorkerThreads && (connectionKeepAliveWorker == null || connectionKeepAliveWorker.IsCompleted))                {                    connectionKeepAliveWorker = new Task(ConnectionKeepAliveWorker, TaskCreationOptions.LongRunning);                    connectionKeepAliveWorker.Start();                }#else                if (!shutdownWorkerThreads && (connectionKeepAliveWorker == null || connectionKeepAliveWorker.ThreadState == ThreadState.Stopped))                {                    connectionKeepAliveWorker = new Thread(ConnectionKeepAliveWorker);                    connectionKeepAliveWorker.Name = "ConnectionKeepAliveWorker";                    connectionKeepAliveWorker.IsBackground = true;                    connectionKeepAliveWorker.Start();                }#endif            }        }
 private static void ConnectionKeepAliveWorker()        {            if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Debug("Connection keep alive polling thread has started.");            DateTime lastPollCheck = DateTime.Now;            while (!shutdownWorkerThreads)            {                try                {#if NET2                    //We have a short sleep here so that we can exit the thread fairly quickly if we need too                    if (ConnectionKeepAlivePollIntervalSecs == int.MaxValue)                        workedThreadSignal.WaitOne(5000, false);                    else                        workedThreadSignal.WaitOne(100, false);#else                    //We have a short sleep here so that we can exit the thread fairly quickly if we need too                    if (ConnectionKeepAlivePollIntervalSecs == int.MaxValue)                        workedThreadSignal.WaitOne(5000);                    else                        workedThreadSignal.WaitOne(100);#endif                    //Check for shutdown here                    if (shutdownWorkerThreads) break;                    //Any connections which we have not seen in the last poll interval get tested using a null packet                    if (ConnectionKeepAlivePollIntervalSecs < int.MaxValue && (DateTime.Now - lastPollCheck).TotalSeconds > (double)ConnectionKeepAlivePollIntervalSecs)                    {                        AllConnectionsSendNullPacketKeepAlive();                        lastPollCheck = DateTime.Now;                    }                }                catch (Exception ex)                {                    LogTools.LogException(ex, "ConnectionKeepAlivePollError");                }            }        }
  private static void AllConnectionsSendNullPacketKeepAlive(bool returnImmediately = false)        {            if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Trace("Starting AllConnectionsSendNullPacketKeepAlive");            //Loop through all connections and test the alive state            List<Connection> allConnections = NetworkComms.GetExistingConnection(ApplicationLayerProtocolStatus.Enabled);            int remainingConnectionCount = allConnections.Count;            QueueItemPriority nullSendPriority = QueueItemPriority.AboveNormal;                        ManualResetEvent allConnectionsComplete = new ManualResetEvent(false);            for (int i = 0; i < allConnections.Count; i++)            {                //We don‘t send null packets to unconnected UDP connections                UDPConnection asUDP = allConnections[i] as UDPConnection;                if (asUDP != null && asUDP.ConnectionUDPOptions == UDPOptions.None)                {                    if (Interlocked.Decrement(ref remainingConnectionCount) == 0)                        allConnectionsComplete.Set();                    continue;                }                else                {                    int innerIndex = i;                    NetworkComms.CommsThreadPool.EnqueueItem(nullSendPriority, new WaitCallback((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 is no need to poll                                    if ((DateTime.Now - allConnections[innerIndex].ConnectionInfo.LastTrafficTime).TotalSeconds > ConnectionKeepAlivePollIntervalSecs)                                        allConnections[innerIndex].SendNullPacket();                                }                                else                                {                                    //If we are client side we wait up to an additional 3 seconds to do the poll                                    //This means the server will 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(ref remainingConnectionCount) == 0)                                allConnectionsComplete.Set();                        }                    }), null);                }            }            //Max wait is 1 seconds per connection            if (!returnImmediately && allConnections.Count > 0)            {#if NET2                if (!allConnectionsComplete.WaitOne(allConnections.Count * 2500, false))#else                if (!allConnectionsComplete.WaitOne(allConnections.Count * 2500))#endif                    //This timeout should not really happen so we are 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.");            }        }

 

原文網址: http://www.cnblogs.com/csdev

介紹開源的.net通訊架構NetworkComms架構之五 心跳檢測

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.