C#SocketAsyncEventArgs实现高效能多并发TCPSocket通信 (客户端实现)

转载自  http://freshflower.iteye.com/blog/2285286


 上一篇讲了服务器端的实现, 这一篇就是客户端的实现.

    服务器实现参考:《C#如何利用SocketAsyncEventArgs实现高效能TCPSocket通信 (服务器实现)》

     与服务器不同的是客户端的实现需要多个SocketAsyncEventArgs共同协作,至少需要两个:接收的只需要一个,发送的需要一个,也可以多个,这在多线程中尤为重要,接下来说明。

 

     客户端一般需要数据的时候,就要发起请求,在多线程环境中,请求服务器一般不希望列队等候,这样会大大拖慢程序的处理。如果发送数据包的SocketAsyncEventArgs只有一个,且当他正在工作的时候, 下一个请求也来访问,这时会抛出异常, 提示当前的套接字正在工作, 所以这不是我们愿意看到, 唯有增加SocketAsyncEventArgs对象来解决。 那么接下来的问题就是我怎么知道当前的SocketAsyncEventArgs对象是否正在工作呢. 很简单,我们新建一个MySocketEventArgs类来继承它。

C#代码   收藏代码
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net.Sockets;  
  5. using System.Text;  
  6.   
  7. namespace Plates.Client.Net  
  8. {  
  9.     class MySocketEventArgs : SocketAsyncEventArgs  
  10.     {  
  11.   
  12.         /// <summary>  
  13.         /// 标识,只是一个编号而已  
  14.         /// </summary>  
  15.         public int ArgsTag { getset; }  
  16.   
  17.         /// <summary>  
  18.         /// 设置/获取使用状态  
  19.         /// </summary>  
  20.         public bool IsUsing { getset; }  
  21.   
  22.     }  
  23. }  

 

     接下来,我们还需要BufferManager类,这个类已经在服务端贴出来了,与服务端是一样的, 再贴一次:

C#代码   收藏代码
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net.Sockets;  
  5. using System.Text;  
  6. using System.Threading.Tasks;  
  7.   
  8. namespace Plates.Client.Net  
  9. {  
  10.     class BufferManager  
  11.     {  
  12.         int m_numBytes;                 // the total number of bytes controlled by the buffer pool  
  13.         byte[] m_buffer;                // the underlying byte array maintained by the Buffer Manager  
  14.         Stack<int> m_freeIndexPool;     //   
  15.         int m_currentIndex;  
  16.         int m_bufferSize;  
  17.   
  18.         public BufferManager(int totalBytes, int bufferSize)  
  19.         {  
  20.             m_numBytes = totalBytes;  
  21.             m_currentIndex = 0;  
  22.             m_bufferSize = bufferSize;  
  23.             m_freeIndexPool = new Stack<int>();  
  24.         }  
  25.   
  26.         // Allocates buffer space used by the buffer pool  
  27.         public void InitBuffer()  
  28.         {  
  29.             // create one big large buffer and divide that   
  30.             // out to each SocketAsyncEventArg object  
  31.             m_buffer = new byte[m_numBytes];  
  32.         }  
  33.   
  34.         // Assigns a buffer from the buffer pool to the   
  35.         // specified SocketAsyncEventArgs object  
  36.         //  
  37.         // <returns>true if the buffer was successfully set, else false</returns>  
  38.         public bool SetBuffer(SocketAsyncEventArgs args)  
  39.         {  
  40.   
  41.             if (m_freeIndexPool.Count > 0)  
  42.             {  
  43.                 args.SetBuffer(m_buffer, m_freeIndexPool.Pop(), m_bufferSize);  
  44.             }  
  45.             else  
  46.             {  
  47.                 if ((m_numBytes - m_bufferSize) < m_currentIndex)  
  48.                 {  
  49.                     return false;  
  50.                 }  
  51.                 args.SetBuffer(m_buffer, m_currentIndex, m_bufferSize);  
  52.                 m_currentIndex += m_bufferSize;  
  53.             }  
  54.             return true;  
  55.         }  
  56.   
  57.         // Removes the buffer from a SocketAsyncEventArg object.    
  58.         // This frees the buffer back to the buffer pool  
  59.         public void FreeBuffer(SocketAsyncEventArgs args)  
  60.         {  
  61.             m_freeIndexPool.Push(args.Offset);  
  62.             args.SetBuffer(null, 0, 0);  
  63.         }  
  64.     }  
  65. }  

 

     接下来是重点实现了,别的不多说,看代码:

 

C#代码   收藏代码
  1. using System;  
  2. using System.Collections;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Net;  
  6. using System.Net.Sockets;  
  7. using System.Text;  
  8. using System.Threading;  
  9. using System.Threading.Tasks;  
  10.   
  11. namespace Plates.Client.Net  
  12. {  
  13.     class SocketManager: IDisposable  
  14.     {  
  15.         private const Int32 BuffSize = 1024;  
  16.   
  17.         // The socket used to send/receive messages.  
  18.         private Socket clientSocket;  
  19.   
  20.         // Flag for connected socket.  
  21.         private Boolean connected = false;  
  22.   
  23.         // Listener endpoint.  
  24.         private IPEndPoint hostEndPoint;  
  25.   
  26.         // Signals a connection.  
  27.         private static AutoResetEvent autoConnectEvent = new AutoResetEvent(false);  
  28.   
  29.         BufferManager m_bufferManager;  
  30.         //定义接收数据的对象  
  31.         List<byte> m_buffer;   
  32.         //发送与接收的MySocketEventArgs变量定义.  
  33.         private List<MySocketEventArgs> listArgs = new List<MySocketEventArgs>();  
  34.         private MySocketEventArgs receiveEventArgs = new MySocketEventArgs();  
  35.         int tagCount = 0;  
  36.   
  37.         /// <summary>  
  38.         /// 当前连接状态  
  39.         /// </summary>  
  40.         public bool Connected { get { return clientSocket != null && clientSocket.Connected; } }  
  41.   
  42.         //服务器主动发出数据受理委托及事件  
  43.         public delegate void OnServerDataReceived(byte[] receiveBuff);  
  44.         public event OnServerDataReceived ServerDataHandler;  
  45.   
  46.         //服务器主动关闭连接委托及事件  
  47.         public delegate void OnServerStop();  
  48.         public event OnServerStop ServerStopEvent;  
  49.   
  50.   
  51.         // Create an uninitialized client instance.  
  52.         // To start the send/receive processing call the  
  53.         // Connect method followed by SendReceive method.  
  54.         internal SocketManager(String ip, Int32 port)  
  55.         {  
  56.             // Instantiates the endpoint and socket.  
  57.             hostEndPoint = new IPEndPoint(IPAddress.Parse(ip), port);  
  58.             clientSocket = new Socket(hostEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);  
  59.             m_bufferManager = new BufferManager(BuffSize * 2, BuffSize);  
  60.             m_buffer = new List<byte>();  
  61.         }  
  62.   
  63.         /// <summary>  
  64.         /// 连接到主机  
  65.         /// </summary>  
  66.         /// <returns>0.连接成功, 其他值失败,参考SocketError的值列表</returns>  
  67.         internal SocketError Connect()  
  68.         {  
  69.             SocketAsyncEventArgs connectArgs = new SocketAsyncEventArgs();  
  70.             connectArgs.UserToken = clientSocket;  
  71.             connectArgs.RemoteEndPoint = hostEndPoint;  
  72.             connectArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnConnect);  
  73.   
  74.             clientSocket.ConnectAsync(connectArgs);  
  75.             autoConnectEvent.WaitOne(); //阻塞. 让程序在这里等待,直到连接响应后再返回连接结果  
  76.             return connectArgs.SocketError;  
  77.         }  
  78.   
  79.         /// Disconnect from the host.  
  80.         internal void Disconnect()  
  81.         {  
  82.             clientSocket.Disconnect(false);  
  83.         }  
  84.   
  85.         // Calback for connect operation  
  86.         private void OnConnect(object sender, SocketAsyncEventArgs e)  
  87.         {  
  88.             // Signals the end of connection.  
  89.             autoConnectEvent.Set(); //释放阻塞.  
  90.             // Set the flag for socket connected.  
  91.             connected = (e.SocketError == SocketError.Success);  
  92.             //如果连接成功,则初始化socketAsyncEventArgs  
  93.             if (connected)   
  94.                 initArgs(e);  
  95.         }  
  96.  
  97.  
  98.         #region args  
  99.   
  100.         /// <summary>  
  101.         /// 初始化收发参数  
  102.         /// </summary>  
  103.         /// <param name="e"></param>  
  104.         private void initArgs(SocketAsyncEventArgs e)  
  105.         {  
  106.             m_bufferManager.InitBuffer();  
  107.             //发送参数  
  108.             initSendArgs();  
  109.             //接收参数  
  110.             receiveEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(IO_Completed);  
  111.             receiveEventArgs.UserToken = e.UserToken;  
  112.             receiveEventArgs.ArgsTag = 0;  
  113.             m_bufferManager.SetBuffer(receiveEventArgs);  
  114.   
  115.             //启动接收,不管有没有,一定得启动.否则有数据来了也不知道.  
  116.             if (!e.ConnectSocket.ReceiveAsync(receiveEventArgs))  
  117.                 ProcessReceive(receiveEventArgs);  
  118.         }  
  119.   
  120.         /// <summary>  
  121.         /// 初始化发送参数MySocketEventArgs  
  122.         /// </summary>  
  123.         /// <returns></returns>  
  124.         MySocketEventArgs initSendArgs()  
  125.         {  
  126.             MySocketEventArgs sendArg = new MySocketEventArgs();  
  127.             sendArg.Completed += new EventHandler<SocketAsyncEventArgs>(IO_Completed);  
  128.             sendArg.UserToken = clientSocket;  
  129.             sendArg.RemoteEndPoint = hostEndPoint;  
  130.             sendArg.IsUsing = false;  
  131.             Interlocked.Increment(ref tagCount);  
  132.             sendArg.ArgsTag = tagCount;  
  133.             lock (listArgs)  
  134.             {  
  135.                 listArgs.Add(sendArg);  
  136.             }  
  137.             return sendArg;  
  138.         }  
  139.   
  140.   
  141.   
  142.         void IO_Completed(object sender, SocketAsyncEventArgs e)  
  143.         {  
  144.             MySocketEventArgs mys = (MySocketEventArgs)e;  
  145.             // determine which type of operation just completed and call the associated handler  
  146.             switch (e.LastOperation)  
  147.             {  
  148.                 case SocketAsyncOperation.Receive:  
  149.                     ProcessReceive(e);  
  150.                     break;  
  151.                 case SocketAsyncOperation.Send:  
  152.                     mys.IsUsing = false//数据发送已完成.状态设为False  
  153.                     ProcessSend(e);  
  154.                     break;  
  155.                 default:  
  156.                     throw new ArgumentException("The last operation completed on the socket was not a receive or send");  
  157.             }  
  158.         }  
  159.   
  160.         // This method is invoked when an asynchronous receive operation completes.   
  161.         // If the remote host closed the connection, then the socket is closed.    
  162.         // If data was received then the data is echoed back to the client.  
  163.         //  
  164.         private void ProcessReceive(SocketAsyncEventArgs e)  
  165.         {  
  166.             try  
  167.             {  
  168.                 // check if the remote host closed the connection  
  169.                 Socket token = (Socket)e.UserToken;  
  170.                 if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)  
  171.                 {  
  172.                     //读取数据  
  173.                     byte[] data = new byte[e.BytesTransferred];  
  174.                     Array.Copy(e.Buffer, e.Offset, data, 0, e.BytesTransferred);  
  175.                     lock (m_buffer)  
  176.                     {  
  177.                         m_buffer.AddRange(data);  
  178.                     }  
  179.   
  180.                     do  
  181.                     {  
  182.                         //注意: 这里是需要和服务器有协议的,我做了个简单的协议,就是一个完整的包是包长(4字节)+包数据,便于处理,当然你可以定义自己需要的;   
  183.                         //判断包的长度,前面4个字节.  
  184.                         byte[] lenBytes = m_buffer.GetRange(0, 4).ToArray();  
  185.                         int packageLen = BitConverter.ToInt32(lenBytes, 0);  
  186.                         if (packageLen <= m_buffer.Count - 4)  
  187.                         {  
  188.                             //包够长时,则提取出来,交给后面的程序去处理  
  189.                             byte[] rev = m_buffer.GetRange(4, packageLen).ToArray();  
  190.                             //从数据池中移除这组数据,为什么要lock,你懂的  
  191.                             lock (m_buffer)  
  192.                             {  
  193.                                 m_buffer.RemoveRange(0, packageLen + 4);  
  194.                             }  
  195.                             //将数据包交给前台去处理  
  196.                             DoReceiveEvent(rev);  
  197.                         }  
  198.                         else  
  199.                         {   //长度不够,还得继续接收,需要跳出循环  
  200.                             break;  
  201.                         }  
  202.                     } while (m_buffer.Count > 4);  
  203.                     //注意:你一定会问,这里为什么要用do-while循环?     
  204.                     //如果当服务端发送大数据流的时候,e.BytesTransferred的大小就会比服务端发送过来的完整包要小,    
  205.                     //需要分多次接收.所以收到包的时候,先判断包头的大小.够一个完整的包再处理.    
  206.                     //如果服务器短时间内发送多个小数据包时, 这里可能会一次性把他们全收了.    
  207.                     //这样如果没有一个循环来控制,那么只会处理第一个包,    
  208.                     //剩下的包全部留在m_buffer中了,只有等下一个数据包过来后,才会放出一个来.  
  209.                     //继续接收  
  210.                     if (!token.ReceiveAsync(e))  
  211.                         this.ProcessReceive(e);  
  212.                 }  
  213.                 else  
  214.                 {  
  215.                     ProcessError(e);  
  216.                 }  
  217.             }  
  218.             catch (Exception xe)  
  219.             {  
  220.                 Console.WriteLine(xe.Message);  
  221.             }  
  222.         }  
  223.   
  224.         // This method is invoked when an asynchronous send operation completes.    
  225.         // The method issues another receive on the socket to read any additional   
  226.         // data sent from the client  
  227.         //  
  228.         // <param name="e"></param>  
  229.         private void ProcessSend(SocketAsyncEventArgs e)  
  230.         {  
  231.             if (e.SocketError != SocketError.Success)  
  232.             {   
  233.                 ProcessError(e);  
  234.             }  
  235.         }  
  236.  
  237.         #endregion  
  238.  
  239.         #region read write  
  240.   
  241.         // Close socket in case of failure and throws  
  242.         // a SockeException according to the SocketError.  
  243.         private void ProcessError(SocketAsyncEventArgs e)  
  244.         {  
  245.             Socket s = (Socket)e.UserToken;  
  246.             if (s.Connected)  
  247.             {  
  248.                 // close the socket associated with the client  
  249.                 try  
  250.                 {  
  251.                     s.Shutdown(SocketShutdown.Both);  
  252.                 }  
  253.                 catch (Exception)  
  254.                 {  
  255.                     // throws if client process has already closed  
  256.                 }  
  257.                 finally  
  258.                 {  
  259.                     if (s.Connected)  
  260.                     {  
  261.                         s.Close();  
  262.                     }  
  263.                     connected = false;  
  264.                 }  
  265.             }  
  266.             //这里一定要记得把事件移走,如果不移走,当断开服务器后再次连接上,会造成多次事件触发.  
  267.             foreach (MySocketEventArgs arg in listArgs)  
  268.                 arg.Completed -= IO_Completed;  
  269.             receiveEventArgs.Completed -= IO_Completed;  
  270.   
  271.             if (ServerStopEvent != null)  
  272.                 ServerStopEvent();  
  273.         }  
  274.   
  275.         // Exchange a message with the host.  
  276.         internal void Send(byte[] sendBuffer)  
  277.         {  
  278.             if (connected)  
  279.             {  
  280.                 //先对数据进行包装,就是把包的大小作为头加入,这必须与服务器端的协议保持一致,否则造成服务器无法处理数据.  
  281.                 byte[] buff = new byte[sendBuffer.Length + 4];  
  282.                 Array.Copy(BitConverter.GetBytes(sendBuffer.Length), buff, 4);  
  283.                 Array.Copy(sendBuffer, 0, buff, 4, sendBuffer.Length);  
  284.                 //查找有没有空闲的发送MySocketEventArgs,有就直接拿来用,没有就创建新的.So easy!  
  285.                 MySocketEventArgs sendArgs = listArgs.Find(a => a.IsUsing == false);  
  286.                 if (sendArgs == null) {  
  287.                     sendArgs = initSendArgs();  
  288.                 }  
  289.                 lock (sendArgs) //要锁定,不锁定让别的线程抢走了就不妙了.  
  290.                 {  
  291.                     sendArgs.IsUsing = true;  
  292.                     sendArgs.SetBuffer(buff, 0, buff.Length);  
  293.                 }  
  294.                 clientSocket.SendAsync(sendArgs);  
  295.             }  
  296.             else  
  297.             {  
  298.                 throw new SocketException((Int32)SocketError.NotConnected);  
  299.             }  
  300.         }  
  301.   
  302.         /// <summary>  
  303.         /// 使用新进程通知事件回调  
  304.         /// </summary>  
  305.         /// <param name="buff"></param>  
  306.         private void DoReceiveEvent(byte[] buff)  
  307.         {  
  308.             if (ServerDataHandler == nullreturn;  
  309.             //ServerDataHandler(buff); //可直接调用.  
  310.             //但我更喜欢用新的线程,这样不拖延接收新数据.  
  311.             Thread thread = new Thread(new ParameterizedThreadStart((obj) =>  
  312.             {  
  313.                 ServerDataHandler((byte[])obj);  
  314.             }));  
  315.             thread.IsBackground = true;  
  316.             thread.Start(buff);  
  317.         }  
  318.  
  319.         #endregion  
  320.  
  321.         #region IDisposable Members  
  322.   
  323.         // Disposes the instance of SocketClient.  
  324.         public void Dispose()  
  325.         {  
  326.             autoConnectEvent.Close();  
  327.             if (clientSocket.Connected)  
  328.             {  
  329.                 clientSocket.Close();  
  330.             }  
  331.         }  
  332.  
  333.         #endregion  
  334.     }  
  335. }  
 

 

 好了, 怎么使用, 那是再简单不过的事了, 当然连接同一个服务器的同一端口, 这个类你只需要初始化一次就可以了, 不要创建多个, 这样太浪费资源. 上面是定义了通讯的基础类, 那么接下来就是把相关的方法再包装一下, 做成供前台方便调用的含有静态方法的类就OK了. 

C#代码   收藏代码
  1. using Newtonsoft.Json;  
  2. using Plates.Common;  
  3. using Plates.Common.Base;  
  4. using Plates.Common.Beans;  
  5. using RuncomLib.File;  
  6. using RuncomLib.Log;  
  7. using RuncomLib.Text;  
  8. using System;  
  9. using System.Collections.Generic;  
  10. using System.Linq;  
  11. using System.Net.Sockets;  
  12. using System.Security.Cryptography;  
  13. using System.Text;  
  14. using System.Threading;  
  15. using System.Timers;  
  16.   
  17. namespace Plates.Client.Net  
  18. {  
  19.     class Request  
  20.     {  
  21.         //定义,最好定义成静态的, 因为我们只需要一个就好  
  22.         static SocketManager smanager = null;  
  23.         static UserInfoModel userInfo = null;  
  24.   
  25.         //定义事件与委托  
  26.         public delegate void ReceiveData(object message);  
  27.         public delegate void ServerClosed();  
  28.         public static event ReceiveData OnReceiveData;  
  29.         public static event ServerClosed OnServerClosed;  
  30.   
  31.         /// <summary>  
  32.         /// 心跳定时器  
  33.         /// </summary>  
  34.         static System.Timers.Timer heartTimer = null;  
  35.         /// <summary>  
  36.         /// 心跳包  
  37.         /// </summary>  
  38.         static ApiResponse heartRes = null;  
  39.   
  40.         /// <summary>  
  41.         /// 判断是否已连接  
  42.         /// </summary>  
  43.         public static bool Connected  
  44.         {  
  45.             get { return smanager != null && smanager.Connected; }   
  46.         }  
  47.   
  48.         /// <summary>  
  49.         /// 已登录的用户信息  
  50.         /// </summary>  
  51.         public static UserInfoModel UserInfo  
  52.         {  
  53.             get { return userInfo; }  
  54.         }  
  55.  
  56.  
  57.         #region 基本方法  
  58.   
  59.         /// <summary>  
  60.         /// 连接到服务器  
  61.         /// </summary>  
  62.         /// <returns></returns>  
  63.         public static SocketError Connect()  
  64.         {  
  65.             if (Connected) return SocketError.Success;  
  66.             //我这里是读取配置,   
  67.             string ip = Config.ReadConfigString("socket""server""");  
  68.             int port = Config.ReadConfigInt("socket""port", 13909);  
  69.             if (string.IsNullOrWhiteSpace(ip) || port <= 1000) return SocketError.Fault;  
  70.    
  71.             //创建连接对象, 连接到服务器  
  72.             smanager = new SocketManager(ip, port);  
  73.             SocketError error = smanager.Connect();  
  74.             if (error == SocketError.Success){  
  75.                //连接成功后,就注册事件. 最好在成功后再注册.  
  76.                 smanager.ServerDataHandler += OnReceivedServerData;  
  77.                 smanager.ServerStopEvent += OnServerStopEvent;  
  78.             }  
  79.             return error;  
  80.         }  
  81.   
  82.         /// <summary>  
  83.         /// 断开连接  
  84.         /// </summary>  
  85.         public static void Disconnect()  
  86.         {  
  87.             try  
  88.             {  
  89.                 smanager.Disconnect();  
  90.             }  
  91.             catch (Exception) { }  
  92.         }  
  93.   
  94.   
  95.         /// <summary>  
  96.         /// 发送请求  
  97.         /// </summary>  
  98.         /// <param name="request"></param>  
  99.         /// <returns></returns>  
  100.         public static bool Send(ApiResponse request)  
  101.         {  
  102.             return Send(JsonConvert.SerializeObject(request));  
  103.         }  
  104.   
  105.         /// <summary>  
  106.         /// 发送消息  
  107.         /// </summary>  
  108.         /// <param name="message">消息实体</param>  
  109.         /// <returns>True.已发送; False.未发送</returns>  
  110.         public static bool Send(string message)  
  111.         {  
  112.             if (!Connected) return false;  
  113.   
  114.             byte[] buff = Encoding.UTF8.GetBytes(message);  
  115.             //加密,根据自己的需要可以考虑把消息加密  
  116.             //buff = AESEncrypt.Encrypt(buff, m_aesKey);  
  117.             smanager.Send(buff);  
  118.             return true;  
  119.         }  
  120.   
  121.   
  122.         /// <summary>  
  123.         /// 发送字节流  
  124.         /// </summary>  
  125.         /// <param name="buff"></param>  
  126.         /// <returns></returns>  
  127.         static bool Send(byte[] buff)  
  128.         {  
  129.             if (!Connected) return false;  
  130.             smanager.Send(buff);  
  131.             return true;  
  132.         }  
  133.   
  134.   
  135.   
  136.         /// <summary>  
  137.         /// 接收消息  
  138.         /// </summary>  
  139.         /// <param name="buff"></param>  
  140.         private static void OnReceivedServerData(byte[] buff)  
  141.         {  
  142.             //To do something  
  143.             //你要处理的代码,可以实现把buff转化成你具体的对象, 再传给前台  
  144.             if (OnReceiveData != null)  
  145.                 OnReceiveData(buff);  
  146.         }  
  147.   
  148.   
  149.   
  150.         /// <summary>  
  151.         /// 服务器已断开  
  152.         /// </summary>  
  153.         private static void OnServerStopEvent()  
  154.         {  
  155.             if (OnServerClosed != null)  
  156.                 OnServerClosed();  
  157.         }  
  158.  
  159.         #endregion  
  160.  
  161.         #region 心跳包  
  162.         //心跳包也是很重要的,看自己的需要了, 我只定义出来, 你自己找个地方去调用吧  
  163.         /// <summary>  
  164.         /// 开启心跳  
  165.         /// </summary>  
  166.         private static void StartHeartbeat()  
  167.         {  
  168.             if (heartTimer == null)  
  169.             {  
  170.                 heartTimer = new System.Timers.Timer();  
  171.                 heartTimer.Elapsed += TimeElapsed;  
  172.             }  
  173.             heartTimer.AutoReset = true;     //循环执行  
  174.             heartTimer.Interval = 30 * 1000; //每30秒执行一次  
  175.             heartTimer.Enabled = true;  
  176.             heartTimer.Start();  
  177.               
  178.             //初始化心跳包  
  179.             heartRes = new ApiResponse((int)ApiCode.心跳);  
  180.             heartRes.data = new Dictionary<stringobject>();  
  181.             heartRes.data.Add("beat", Function.Base64Encode(userInfo.nickname + userInfo.userid + DateTime.Now.ToString("HH:mm:ss")));  
  182.         }  
  183.   
  184.         /// <summary>  
  185.         /// 定时执行  
  186.         /// </summary>  
  187.         /// <param name="source"></param>  
  188.         /// <param name="e"></param>  
  189.         static void TimeElapsed(object source, ElapsedEventArgs e)  
  190.         {  
  191.             Request.Send(heartRes);  
  192.         }  
  193.  
  194.         #endregion  
  195.     }  
  196. }  

 

好了, 就这些, 所有的请求都是异步进行的, 如果你想同步进行, 我也有实现过, 等有空了再贴上来.

如果你还没有弄懂服务器端, 请进入:

服务器实现参考:《C#如何利用SocketAsyncEventArgs实现高效能TCPSocket通信 (服务器实现)》


  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
注:更多资料请根据压缩文件中的《更多资料.txt》文件的介绍免费获取 =====★★★★史上最全的IOCP资料大全★★★★============== 目的:研究和分享基于IOCP通讯模型的服务器端及即时通讯客户端相关技术 语言:Delphi\C++ 欢迎给位朋友加入 -------------------------前言------------------------ 最近在编写即时通讯工具,于是便参考和搜罗了网上大量的文章和源码, 对IOCP涉及的相关技术进行了广泛和深入的研究。 IOCP涉及的关键知识点有很多很多,这方面的文章也非常多, 但是很多讲述的都是某方面的,为了帮大家甄选资料,我决定分享给大家。 以下是我搜集的部分IOCP相关的资料目录,有需要的请加我QQ和QQ群,无偿分享: --------------------------IOCP部分相关知识点------------------ 线程池,Socket连接池、数据库连接池、内存池及内存管理 防DDos攻击、防只连接不发送消息及Setsockopt相关设置 WSAENOBUFS及0缓冲的WSARecive投递 优雅的链接关闭方法及shutdown、TIME_WAIT 及注册表设置:TcpNumConnections/MaxUserPort 多核多线程、生产消费者模型、读写者模型、多线程无锁环形队列及LockFreeList概念 Socket重用、端口重用 心跳、粘包、乱序 ------------------------我收集的文章及源码的部分目录---------------------- ------------------------供大家搜索资料时参考----------------------------------
### 回答1: 基于SocketAsyncEventArgs的高并发客户端是一种用于处理大量客户端连接的异步编程模型。SocketAsyncEventArgs类提供了高效的网络通信操作,可以处理多个客户端的请求,并且能够在不阻塞主线程的情况下同时处理多个请求。 在构建一个基于SocketAsyncEventArgs的高并发客户端时,需要以下步骤: 1. 创建一个SocketAsyncEventArgs对象的池,用于存储可重复使用的SocketAsyncEventArgs实例。这个池的大小可以根据需求进行配置,通常是根据服务器的负载和性能来确定。 2. 创建一个SocketAsyncEventArgs对象的工作队列,用于存储待处理的客户端请求。当客户端连接到服务器时,将创建一个SocketAsyncEventArgs实例,并将其加入到工作队列中。 3. 创建一个监听套接字,用于接受新的客户端连接。当有新的客户端连接时,将从SocketAsyncEventArgs对象池中获取一个可用的SocketAsyncEventArgs实例,并使用该实例处理该客户端的请求。 4. 在处理客户端请求的SocketAsyncEventArgs实例中,可以使用异步方法来执行读取、写入和关闭操作。这样可以确保在处理一个请求时,不会阻塞其他请求的处理,并且可以充分利用系统资源。 5. 当请求处理完成后,将SocketAsyncEventArgs实例重置,并将其返回到SocketAsyncEventArgs对象池中,以便可以被其他请求重用。 通过以上步骤,可以实现一个基于SocketAsyncEventArgs的高并发客户端,能够有效处理多个客户端的请求,并提供高性能和可扩展性。同时,使用异步编程模型可以最大限度地提高系统的并发能力和响应速度。 ### 回答2: 基于SocketAsyncEventArgs的高并发客户端是一种使用异步Socket编程模型来处理大量并发连接的技术。SocketAsyncEventArgs是.NET Framework提供的一个高性能的异步网络编程组件。 基于SocketAsyncEventArgs的高并发客户端可以实现以下功能: 1. 同时处理多个连接请求:通过使用SocketAsyncEventArgs对象池,可以预先创建多个SocketAsyncEventArgs对象并复用它们来处理多个客户端连接请求,从而实现并发处理能力。 2. 异步接收和发送数据:使用SocketAsyncEventArgs的异步方法,可以实现高效的数据传输,避免了传统的同步I/O方式中的线程阻塞等待问题。 3. 使用IOCP模型提升性能:SocketAsyncEventArgs内部使用IOCP(I/O完成端口)模型来实现异步操作,这种模型可以减少系统开销,并提高并发处理能力。 4. 支持连接池管理:通过使用连接池管理SocketAsyncEventArgs对象,可以灵活地管理客户端连接,包括创建、回收和释放等,以提高连接的复用性和资源的有效利用。 基于SocketAsyncEventArgs的高并发客户端适用于需要同时处理大量客户端连接请求的场景,如高性能服务器、网络游戏服务器等。它可以通过有效地利用异步I/O和IOCP模型来实现并发处理能力,提高系统的吞吐量和响应速度。 总之,基于SocketAsyncEventArgs的高并发客户端是一种使用异步Socket编程模型来实现高性能、高并发处理的技术,通过预先创建和复用SocketAsyncEventArgs对象、异步操作和使用IOCP模型等手段,可以实现高效的数据传输和同时处理多个连接请求的能力。 ### 回答3: 基于SocketAsyncEventArgs的高并发客户端可以使用异步编程模型来实现。在传统的同步模型下,每个客户端连接都需要创建一个新的线程,当并发量较高时,线程的创建和销毁会带来较大的开销,导致服务器性能下降。 而使用SocketAsyncEventArgs实现并发客户端,则可以避免频繁的线程创建和销毁,提高服务器的并发处理能力。基于SocketAsyncEventArgs,可以使用对象池来管理SocketAsyncEventArgs对象的创建和回收,避免频繁的GC开销,提高性能。 在基于SocketAsyncEventArgs的高并发客户端中,可以使用异步方法来接收和发送数据。通过BeginReceive和BeginSend方法,可以异步的从客户端接收和发送数据,而不会阻塞主线程,提高性能。 此外,还可以使用AsyncAwait异步编程模式来处理异步操作,将回调函数改写为异步方法,使代码更加简洁易读。 在处理高并发时,需要注意资源的合理利用和线程的调度。可以使用线程池来管理任务的调度,避免线程的频繁创建和销毁。同时,要正确处理多线程下的共享资源,避免出现竞争条件和死锁等问题。 综上所述,基于SocketAsyncEventArgs的高并发客户端可以极大地提高服务器的性能和并发处理能力,有效避免了多线程带来的开销问题。同时,需要合理利用异步编程模型、对象池和线程池等技术手段来实现高效的并发处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值