C#高性能大容量SOCKET并发(六):超时Socket断开(守护线程)和心跳包

守护线程

在服务端版Socket编程需要处理长时间没有发送数据的Socket,需要在超时多长时间后断开连接,我们需要独立一个线程(DaemonThread)来轮询,在执行断开时,需要把Socket对象锁定,并调用CloseClientSocket来断开连接,具体处理代码如下:

[csharp] view plain copy
  1. namespace SocketAsyncSvr  
  2. {  
  3.     class DaemonThread : Object  
  4.     {  
  5.         private Thread m_thread;  
  6.         private AsyncSocketServer m_asyncSocketServer;  
  7.   
  8.         public DaemonThread(AsyncSocketServer asyncSocketServer)  
  9.         {  
  10.             m_asyncSocketServer = asyncSocketServer;  
  11.             m_thread = new Thread(DaemonThreadStart);  
  12.             m_thread.Start();  
  13.         }  
  14.   
  15.         public void DaemonThreadStart()  
  16.         {  
  17.             while (m_thread.IsAlive)  
  18.             {  
  19.                 AsyncSocketUserToken[] userTokenArray = null;  
  20.                 m_asyncSocketServer.AsyncSocketUserTokenList.CopyList(ref userTokenArray);  
  21.                 for (int i = 0; i < userTokenArray.Length; i++)  
  22.                 {  
  23.                     if (!m_thread.IsAlive)  
  24.                         break;  
  25.                     try  
  26.                     {  
  27.                         if ((DateTime.Now - userTokenArray[i].ActiveDateTime).Milliseconds > m_asyncSocketServer.SocketTimeOutMS) //超时Socket断开  
  28.                         {  
  29.                             lock (userTokenArray[i])  
  30.                             {  
  31.                                 m_asyncSocketServer.CloseClientSocket(userTokenArray[i]);  
  32.                             }  
  33.                         }  
  34.                     }                      
  35.                     catch (Exception E)  
  36.                     {  
  37.                         Program.Logger.ErrorFormat("Daemon thread check timeout socket error, message: {0}", E.Message);  
  38.                         Program.Logger.Error(E.StackTrace);  
  39.                     }  
  40.                 }  
  41.   
  42.                 for (int i = 0; i < 60 * 1000 / 10; i++) //每分钟检测一次  
  43.                 {  
  44.                     if (!m_thread.IsAlive)  
  45.                         break;  
  46.                     Thread.Sleep(10);  
  47.                 }  
  48.             }  
  49.         }  
  50.   
  51.         public void Close()  
  52.         {  
  53.             m_thread.Abort();  
  54.             m_thread.Join();  
  55.         }  
  56.     }  
  57. }  

心跳包

有超时连接,相对应的需要设计心跳包,心跳包用来检测连接和维护连接状态,心跳包的原理是客户端发送一个包给服务器,服务器收到后发一个响应包给客户端,通过检测是否有返回来判断连接是否正常,心跳包实现放在BaseSocketProtocol.DoActive方法中。

[csharp] view plain copy
  1. public bool DoActive()  
  2. {  
  3.     m_outgoingDataAssembler.AddSuccess();  
  4.     return DoSendResult();  
  5. }  

具体由各个协议是否决定调用,如控制协议ControlSocketProtocol实现心跳协议如下:

[csharp] view plain copy
  1. public override bool ProcessCommand(byte[] buffer, int offset, int count) //处理分完包的数据,子类从这个方法继承  
  2. {  
  3.     ControlSocketCommand command = StrToCommand(m_incomingDataParser.Command);  
  4.     m_outgoingDataAssembler.Clear();  
  5.     m_outgoingDataAssembler.AddResponse();  
  6.     m_outgoingDataAssembler.AddCommand(m_incomingDataParser.Command);  
  7.     if (!CheckLogined(command)) //检测登录  
  8.     {  
  9.         m_outgoingDataAssembler.AddFailure(ProtocolCode.UserHasLogined, "");  
  10.         return DoSendResult();  
  11.     }  
  12.     if (command == ControlSocketCommand.Login)  
  13.         return DoLogin();  
  14.     else if (command == ControlSocketCommand.Active)  
  15.         return DoActive();  
  16.     else if (command == ControlSocketCommand.GetClients)  
  17.         return DoGetClients();  
  18.     else  
  19.     {  
  20.         Program.Logger.Error("Unknow command: " + m_incomingDataParser.Command);  
  21.         return false;  
  22.     }  
  23. }  
DEMO下载地址: http://download.csdn.net/detail/sqldebug_fan/7467745
免责声明:此代码只是为了演示C#完成端口编程,仅用于学习和研究,切勿用于商业用途。水平有限,C#也属于初学,错误在所难免,欢迎指正和指导。邮箱地址:[email protected]

猜你喜欢

转载自blog.csdn.net/andrewniu/article/details/80234515
今日推荐