C#高性能大容量SOCKET并发(三):接收、发送

异步数据接收有可能收到的数据不是一个完整包,或者接收到的数据超过一个包的大小,因此我们需要把接收的数据进行缓存。异步发送我们也需要把每个发送的包加入到一个队列,然后通过队列逐个发送出去,如果每个都实时发送,有可能造成上一个数据包未发送完成,这时再调用SendAsync会抛出异常,提示SocketAsyncEventArgs正在进行异步操作,因此我们需要建立接收缓存和发送缓存。

接收

通过Completed事件响应后调用AsyncSocketInvokeElement.ProcessReceive,在ProcessReceive中,我们把收到数据先写入一个缓存,然后进行分包,分包后压给包处理函数ProcessPacket,ProcessPacket函数然后调用ProcessCommand处理具体的命令,也是各个协议实现业务逻辑的地方,具体代码如下:

[csharp] view plain copy
  1. public virtual bool ProcessReceive(byte[] buffer, int offset, int count) //接收异步事件返回的数据,用于对数据进行缓存和分包  
  2. {  
  3.     m_activeDT = DateTime.UtcNow;  
  4.     DynamicBufferManager receiveBuffer = m_asyncSocketUserToken.ReceiveBuffer;  
  5.   
  6.     receiveBuffer.WriteBuffer(buffer, offset, count);  
  7.     if (receiveBuffer.DataCount > sizeof(int))  
  8.     {  
  9.         //按照长度分包  
  10.         int packetLength = BitConverter.ToInt32(receiveBuffer.Buffer, 0); //获取包长度  
  11.         if (NetByteOrder)  
  12.             packetLength = System.Net.IPAddress.NetworkToHostOrder(packetLength); //把网络字节顺序转为本地字节顺序  
  13.   
  14.   
  15.         if ((packetLength > 10 * 1024 * 1024) | (receiveBuffer.DataCount > 10 * 1024 * 1024)) //最大Buffer异常保护  
  16.             return false;  
  17.   
  18.         if ((receiveBuffer.DataCount - sizeof(int)) >= packetLength) //收到的数据达到包长度  
  19.         {  
  20.             bool result = ProcessPacket(receiveBuffer.Buffer, sizeof(int), packetLength);  
  21.             if (result)  
  22.                 receiveBuffer.Clear(packetLength + sizeof(int)); //从缓存中清理  
  23.             return result;  
  24.         }  
  25.         else  
  26.         {  
  27.             return true;  
  28.         }  
  29.     }  
  30.     else  
  31.     {  
  32.         return true;  
  33.     }  
  34. }  
  35.   
  36. public virtual bool ProcessPacket(byte[] buffer, int offset, int count) //处理分完包后的数据,把命令和数据分开,并对命令进行解析  
  37. {  
  38.     if (count < sizeof(int))  
  39.         return false;  
  40.     int commandLen = BitConverter.ToInt32(buffer, offset); //取出命令长度  
  41.     string tmpStr = Encoding.UTF8.GetString(buffer, offset + sizeof(int), commandLen);  
  42.     if (!m_incomingDataParser.DecodeProtocolText(tmpStr)) //解析命令  
  43.       return false;  
  44.   
  45.     return ProcessCommand(buffer, offset + sizeof(int) + commandLen, count - sizeof(int) - commandLen); //处理命令  
  46. }  
  47.   
  48. public virtual bool ProcessCommand(byte[] buffer, int offset, int count) //处理具体命令,子类从这个方法继承,buffer是收到的数据  
  49. {  
  50.     return true;  
  51. }  

发送

通过Completed事件响应后调用AsyncSocketInvokeElement.SendCompleted,在SendCompleted中我们需要在队列中清除已发送的包,并检测是否还有剩余需要发送的数据包,如果有,则继续发送,具体实现如下:

[csharp] view plain copy
  1. public virtual bool SendCompleted()  
  2. {  
  3.     m_activeDT = DateTime.UtcNow;  
  4.     m_sendAsync = false;  
  5.     AsyncSendBufferManager asyncSendBufferManager = m_asyncSocketUserToken.SendBuffer;  
  6.     asyncSendBufferManager.ClearFirstPacket(); //清除已发送的包  
  7.     int offset = 0;  
  8.     int count = 0;  
  9.     if (asyncSendBufferManager.GetFirstPacket(ref offset, ref count))  
  10.     {  
  11.         m_sendAsync = true;  
  12.         return m_asyncSocketServer.SendAsyncEvent(m_asyncSocketUserToken.ConnectSocket, m_asyncSocketUserToken.SendEventArgs,  
  13.             asyncSendBufferManager.DynamicBufferManager.Buffer, offset, count);  
  14.     }  
  15.     else  
  16.         return SendCallback();  
  17. }  
  18.   
  19. //发送回调函数,用于连续下发数据  
  20. public virtual bool SendCallback()  
  21. {  
  22.     return true;  
  23. }  
在AsyncSocketInvokeElement中提供函数给子类发送数据,业务逻辑是把当前数据包写入缓存,并检测当前是否正在发送包,如果正在发送,则等待回调,如果没有正在发送的数据包,则投递发送请求。

[csharp] view plain copy
  1. public bool DoSendResult()  
  2. {  
  3.     string commandText = m_outgoingDataAssembler.GetProtocolText();  
  4.     byte[] bufferUTF8 = Encoding.UTF8.GetBytes(commandText);  
  5.     int totalLength = sizeof(int) + bufferUTF8.Length; //获取总大小  
  6.     AsyncSendBufferManager asyncSendBufferManager = m_asyncSocketUserToken.SendBuffer;  
  7.     asyncSendBufferManager.StartPacket();  
  8.     asyncSendBufferManager.DynamicBufferManager.WriteInt(totalLength, false); //写入总大小  
  9.     asyncSendBufferManager.DynamicBufferManager.WriteInt(bufferUTF8.Length, false); //写入命令大小  
  10.     asyncSendBufferManager.DynamicBufferManager.WriteBuffer(bufferUTF8); //写入命令内容  
  11.     asyncSendBufferManager.EndPacket();  
  12.   
  13.     bool result = true;  
  14.     if (!m_sendAsync)  
  15.     {  
  16.         int packetOffset = 0;  
  17.         int packetCount = 0;  
  18.         if (asyncSendBufferManager.GetFirstPacket(ref packetOffset, ref packetCount))  
  19.         {  
  20.             m_sendAsync = true;  
  21.             result = m_asyncSocketServer.SendAsyncEvent(m_asyncSocketUserToken.ConnectSocket, m_asyncSocketUserToken.SendEventArgs,   
  22.                 asyncSendBufferManager.DynamicBufferManager.Buffer, packetOffset, packetCount);  
  23.         }                  
  24.     }  
  25.     return result;  
  26. }  
  27.   
  28. public bool DoSendResult(byte[] buffer, int offset, int count)  
  29. {  
  30.     string commandText = m_outgoingDataAssembler.GetProtocolText();  
  31.     byte[] bufferUTF8 = Encoding.UTF8.GetBytes(commandText);  
  32.     int totalLength = sizeof(int) + bufferUTF8.Length + count; //获取总大小  
  33.     AsyncSendBufferManager asyncSendBufferManager = m_asyncSocketUserToken.SendBuffer;  
  34.     asyncSendBufferManager.StartPacket();  
  35.     asyncSendBufferManager.DynamicBufferManager.WriteInt(totalLength, false); //写入总大小  
  36.     asyncSendBufferManager.DynamicBufferManager.WriteInt(bufferUTF8.Length, false); //写入命令大小  
  37.     asyncSendBufferManager.DynamicBufferManager.WriteBuffer(bufferUTF8); //写入命令内容  
  38.     asyncSendBufferManager.DynamicBufferManager.WriteBuffer(buffer, offset, count); //写入二进制数据  
  39.     asyncSendBufferManager.EndPacket();  
  40.   
  41.     bool result = true;  
  42.     if (!m_sendAsync)  
  43.     {  
  44.         int packetOffset = 0;  
  45.         int packetCount = 0;  
  46.         if (asyncSendBufferManager.GetFirstPacket(ref packetOffset, ref packetCount))  
  47.         {  
  48.             m_sendAsync = true;  
  49.             result = m_asyncSocketServer.SendAsyncEvent(m_asyncSocketUserToken.ConnectSocket, m_asyncSocketUserToken.SendEventArgs,   
  50.                 asyncSendBufferManager.DynamicBufferManager.Buffer, packetOffset, packetCount);  
  51.         }  
  52.     }  
  53.     return result;  
  54. }  
  55.   
  56. public bool DoSendBuffer(byte[] buffer, int offset, int count)  
  57. {  
  58.     AsyncSendBufferManager asyncSendBufferManager = m_asyncSocketUserToken.SendBuffer;  
  59.     asyncSendBufferManager.StartPacket();  
  60.     asyncSendBufferManager.DynamicBufferManager.WriteBuffer(buffer, offset, count);  
  61.     asyncSendBufferManager.EndPacket();  
  62.   
  63.     bool result = true;  
  64.     if (!m_sendAsync)  
  65.     {  
  66.         int packetOffset = 0;  
  67.         int packetCount = 0;  
  68.         if (asyncSendBufferManager.GetFirstPacket(ref packetOffset, ref packetCount))  
  69.         {  
  70.             m_sendAsync = true;  
  71.             result = m_asyncSocketServer.SendAsyncEvent(m_asyncSocketUserToken.ConnectSocket, m_asyncSocketUserToken.SendEventArgs,   
  72.                 asyncSendBufferManager.DynamicBufferManager.Buffer, packetOffset, packetCount);  
  73.         }  
  74.     }  
  75.     return result;  
  76. }  

DEMO下载地址: http://download.csdn.net/detail/sqldebug_fan/7467745
免责声明:此代码只是为了演示C#完成端口编程,仅用于学习和研究,切勿用于商业用途。水平有限,C#也属于初学,错误在所难免,欢迎指正和指导。邮箱地址:[email protected]

猜你喜欢

转载自blog.csdn.net/andrewniu/article/details/80229010