天天看點

TCP之心跳包實作思路

說起網絡應用程式設計,想到最多的就是聊天類的軟體。當然,在這類軟體中,一般都會有一個使用者掉線檢測功能。今天我們就通過使用自定義的HeartBeat方式來檢測使用者的掉線情況。

心跳包實作思路

我們采用的思路是:用戶端連接配接上服務端以後,服務端維護一個線上使用者字典,用戶端每隔一段時間,向伺服器發送一個心跳包,伺服器接收到包以後,字典 資料的值都會更新為0;一旦服務端超過規定時間沒有接收到用戶端發來的包,字典資料将會遞增加一,當字典資料的值累計大于等于三,則視為掉線。

TCP之心跳包實作思路

代碼邏輯

用戶端每隔一段時間,發送一個心跳包:

TCP之心跳包實作思路
TCP之心跳包實作思路

 View Code

#region 心跳Timer計數事件

private void heartbeatTimer_Tick(object sender, EventArgs e)

{

currentCount++;

if (currentCount == heartbeatCount)

txtMessage.Append("開始發送心跳包");

MessageEntity entity = new MessageEntity();

entity.MessageType = MessagePicks.Heartbeat;

entity.NickName = loginName;

WriteToStream(entity);

currentCount = 0;

}

#endregion

TCP之心跳包實作思路

在服務端,會開啟一個定時器,定時将userOnLineCounter中的值遞增加一。如果此時收到用戶端的心跳包,則将userOnLineCounter中的值重置。

TCP之心跳包實作思路
TCP之心跳包實作思路

tickCountInStep++;

if (tickCountInStep == tickCount)

if (userCollection.Count > 0)

//計數器自動遞增

expiryCountInStep++;

foreach (User user in userLists)

userOnLineCounter[user]++;

//連續監測三次之後,開始監測集合中的掉線情況

if (expiryCountInStep == expiryCount)

//尋找集合中“掉線”的使用者

var disconnectedUsers = userOnLineCounter.Where(p => p.Value >= 3).ToList();

foreach (var disconnectedUser in disconnectedUsers)

txtLog.Append("使用者" + disconnectedUser.Key.name + "掉線!");

//删除集合中被視為掉線的使用者

userLists.Remove(disconnectedUser.Key);

userOnLineCounter.Remove(disconnectedUser.Key);

//開始廣播發送掉線使用者

entity.MessageType = MessagePicks.OffLine;

EndPoint curOfflineUserEP = disconnectedUser.Key.client.Client.RemoteEndPoint;

string userName = disconnectedUser.Key.name;

entity.MessageContentEx.Add(curOfflineUserEP, userName);

ObjectInversion inversion = new ObjectInversion();

byte[] byteArr = inversion.SerializeTo((object)entity);

try

user.writer.Write(byteArr);

user.writer.Flush();

catch { }

expiryCountInStep = 0;

tickCountInStep = 0;

TCP之心跳包實作思路

收到用戶端心跳包,自動重置計數器。

TCP之心跳包實作思路
TCP之心跳包實作思路

case MessagePicks.Heartbeat:

txtLog.Append("收到用戶端" + entity.NickName + "的心跳回應包.");

if (userOnLineCounter.ContainsKey(user))

userOnLineCounter[user] = 0;

else

userOnLineCounter.Add(user, 0);

break;

TCP之心跳包實作思路

效果圖

TCP之心跳包實作思路

(圖1:三個用戶端連接配接一個伺服器)

TCP之心跳包實作思路

(圖2:使用者“上善若水”掉線)

TCP之心跳包實作思路

(圖3:使用者“古道熱腸”掉線)

 程式暫時還未完全完成,有需要的可以參考下。當然也期待大家的各種思路。

代碼很醜,期望大家指點下重構的方法。

源碼下載下傳

<a href="http://files.cnblogs.com/scy251147/ChattingSolution%2820130922%29.rar">點選這裡下載下傳</a>

    

本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接配接,否則保留追究法律責任的權利。

版權資訊

繼續閱讀