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

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

接收

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

        public virtual bool ProcessReceive(byte[] buffer, int offset, int count) //接收异步事件返回的数据,用于对数据进行缓存和分包
{
m_activeDT = DateTime.UtcNow;
DynamicBufferManager receiveBuffer = m_asyncSocketUserToken.ReceiveBuffer; receiveBuffer.WriteBuffer(buffer, offset, count);
if (receiveBuffer.DataCount > sizeof(int))
{
//按照长度分包
int packetLength = BitConverter.ToInt32(receiveBuffer.Buffer, 0); //获取包长度
if (NetByteOrder)
packetLength = System.Net.IPAddress.NetworkToHostOrder(packetLength); //把网络字节顺序转为本地字节顺序 if ((packetLength > 10 * 1024 * 1024) | (receiveBuffer.DataCount > 10 * 1024 * 1024)) //最大Buffer异常保护
return false; if ((receiveBuffer.DataCount - sizeof(int)) >= packetLength) //收到的数据达到包长度
{
bool result = ProcessPacket(receiveBuffer.Buffer, sizeof(int), packetLength);
if (result)
receiveBuffer.Clear(packetLength + sizeof(int)); //从缓存中清理
return result;
}
else
{
return true;
}
}
else
{
return true;
}
} public virtual bool ProcessPacket(byte[] buffer, int offset, int count) //处理分完包后的数据,把命令和数据分开,并对命令进行解析
{
if (count < sizeof(int))
return false;
int commandLen = BitConverter.ToInt32(buffer, offset); //取出命令长度
string tmpStr = Encoding.UTF8.GetString(buffer, offset + sizeof(int), commandLen);
if (!m_incomingDataParser.DecodeProtocolText(tmpStr)) //解析命令
return false; return ProcessCommand(buffer, offset + sizeof(int) + commandLen, count - sizeof(int) - commandLen); //处理命令
} public virtual bool ProcessCommand(byte[] buffer, int offset, int count) //处理具体命令,子类从这个方法继承,buffer是收到的数据
{
return true;
}

发送

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

        public virtual bool SendCompleted()
{
m_activeDT = DateTime.UtcNow;
m_sendAsync = false;
AsyncSendBufferManager asyncSendBufferManager = m_asyncSocketUserToken.SendBuffer;
asyncSendBufferManager.ClearFirstPacket(); //清除已发送的包
int offset = 0;
int count = 0;
if (asyncSendBufferManager.GetFirstPacket(ref offset, ref count))
{
m_sendAsync = true;
return m_asyncSocketServer.SendAsyncEvent(m_asyncSocketUserToken.ConnectSocket, m_asyncSocketUserToken.SendEventArgs,
asyncSendBufferManager.DynamicBufferManager.Buffer, offset, count);
}
else
return SendCallback();
} //发送回调函数,用于连续下发数据
public virtual bool SendCallback()
{
return true;
}

在AsyncSocketInvokeElement中提供函数给子类发送数据,业务逻辑是把当前数据包写入缓存,并检测当前是否正在发送包,如果正在发送,则等待回调,如果没有正在发送的数据包,则投递发送请求。

        public bool DoSendResult()
{
string commandText = m_outgoingDataAssembler.GetProtocolText();
byte[] bufferUTF8 = Encoding.UTF8.GetBytes(commandText);
int totalLength = sizeof(int) + bufferUTF8.Length; //获取总大小
AsyncSendBufferManager asyncSendBufferManager = m_asyncSocketUserToken.SendBuffer;
asyncSendBufferManager.StartPacket();
asyncSendBufferManager.DynamicBufferManager.WriteInt(totalLength, false); //写入总大小
asyncSendBufferManager.DynamicBufferManager.WriteInt(bufferUTF8.Length, false); //写入命令大小
asyncSendBufferManager.DynamicBufferManager.WriteBuffer(bufferUTF8); //写入命令内容
asyncSendBufferManager.EndPacket(); bool result = true;
if (!m_sendAsync)
{
int packetOffset = 0;
int packetCount = 0;
if (asyncSendBufferManager.GetFirstPacket(ref packetOffset, ref packetCount))
{
m_sendAsync = true;
result = m_asyncSocketServer.SendAsyncEvent(m_asyncSocketUserToken.ConnectSocket, m_asyncSocketUserToken.SendEventArgs,
asyncSendBufferManager.DynamicBufferManager.Buffer, packetOffset, packetCount);
}
}
return result;
} public bool DoSendResult(byte[] buffer, int offset, int count)
{
string commandText = m_outgoingDataAssembler.GetProtocolText();
byte[] bufferUTF8 = Encoding.UTF8.GetBytes(commandText);
int totalLength = sizeof(int) + bufferUTF8.Length + count; //获取总大小
AsyncSendBufferManager asyncSendBufferManager = m_asyncSocketUserToken.SendBuffer;
asyncSendBufferManager.StartPacket();
asyncSendBufferManager.DynamicBufferManager.WriteInt(totalLength, false); //写入总大小
asyncSendBufferManager.DynamicBufferManager.WriteInt(bufferUTF8.Length, false); //写入命令大小
asyncSendBufferManager.DynamicBufferManager.WriteBuffer(bufferUTF8); //写入命令内容
asyncSendBufferManager.DynamicBufferManager.WriteBuffer(buffer, offset, count); //写入二进制数据
asyncSendBufferManager.EndPacket(); bool result = true;
if (!m_sendAsync)
{
int packetOffset = 0;
int packetCount = 0;
if (asyncSendBufferManager.GetFirstPacket(ref packetOffset, ref packetCount))
{
m_sendAsync = true;
result = m_asyncSocketServer.SendAsyncEvent(m_asyncSocketUserToken.ConnectSocket, m_asyncSocketUserToken.SendEventArgs,
asyncSendBufferManager.DynamicBufferManager.Buffer, packetOffset, packetCount);
}
}
return result;
} public bool DoSendBuffer(byte[] buffer, int offset, int count)
{
AsyncSendBufferManager asyncSendBufferManager = m_asyncSocketUserToken.SendBuffer;
asyncSendBufferManager.StartPacket();
asyncSendBufferManager.DynamicBufferManager.WriteBuffer(buffer, offset, count);
asyncSendBufferManager.EndPacket(); bool result = true;
if (!m_sendAsync)
{
int packetOffset = 0;
int packetCount = 0;
if (asyncSendBufferManager.GetFirstPacket(ref packetOffset, ref packetCount))
{
m_sendAsync = true;
result = m_asyncSocketServer.SendAsyncEvent(m_asyncSocketUserToken.ConnectSocket, m_asyncSocketUserToken.SendEventArgs,
asyncSendBufferManager.DynamicBufferManager.Buffer, packetOffset, packetCount);
}
}
return result;
}

DEMO下载地址:http://download.csdn.net/detail/sqldebug_fan/7467745

免责声明:此代码只是为了演示C#完成端口编程,仅用于学习和研究,切勿用于商业用途。水平有限,C#也属于初学,错误在所难免,欢迎指正和指导。邮箱地址:fansheng_hx@163.com。

C#高性能大容量SOCKET并发(三):接收、发送的更多相关文章

  1. C#高性能大容量SOCKET并发(转)

    C#高性能大容量SOCKET并发(零):代码结构说明 C#高性能大容量SOCKET并发(一):IOCP完成端口例子介绍 C#高性能大容量SOCKET并发(二):SocketAsyncEventArgs ...

  2. C#高性能大容量SOCKET并发(十一):编写上传客户端

    原文:C#高性能大容量SOCKET并发(十一):编写上传客户端 客户端封装整体框架 客户端编程基于阻塞同步模式,只有数据正常发送或接收才返回,如果发生错误则抛出异常,基于TcpClient进行封装,主 ...

  3. C#高性能大容量SOCKET并发(零):代码结构说明

    原文:C#高性能大容量SOCKET并发(零):代码结构说明 C#版完成端口具有以下特点: 连接在线管理(提供在线连接维护,连接会话管理,数据接收,连接断开等相关事件跟踪): 发送数据智能合并(组件会根 ...

  4. C#高性能大容量SOCKET并发(五):粘包、分包、解包

    原文:C#高性能大容量SOCKET并发(五):粘包.分包.解包 粘包 使用TCP长连接就会引入粘包的问题,粘包是指发送方发送的若干包数据到接收方接收时粘成一包,从接收缓冲区看,后一包数据的头紧接着前一 ...

  5. C#高性能大容量SOCKET并发(四):缓存设计

    原文:C#高性能大容量SOCKET并发(四):缓存设计 在编写服务端大并发的应用程序,需要非常注意缓存设计,缓存的设计是一个折衷的结果,需要通过并发测试反复验证.有很多服务程序是在启动时申请足够的内存 ...

  6. C#高性能大容量SOCKET并发(二):SocketAsyncEventArgs封装

    原文:C#高性能大容量SOCKET并发(二):SocketAsyncEventArgs封装 1.SocketAsyncEventArgs介绍 SocketAsyncEventArgs是微软提供的高性能 ...

  7. C#高性能大容量SOCKET并发(九):断点续传

    原文:C#高性能大容量SOCKET并发(九):断点续传 上传断点续传 断点续传主要是用在上传或下载文件,一般做法是开始上传的时候,服务器返回上次已经上传的大小,如果上传完成,则返回-1:下载开始的时候 ...

  8. C#高性能大容量SOCKET并发(七):协议字符集

    原文:C#高性能大容量SOCKET并发(七):协议字符集 UTF-8 UTF-8是UNICODE的一种变长字符编码又称万国码,由Ken Thompson于1992年创建.现在已经标准化为RFC 362 ...

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

    原文:C#高性能大容量SOCKET并发(六):超时Socket断开(守护线程)和心跳包 守护线程 在服务端版Socket编程需要处理长时间没有发送数据的Socket,需要在超时多长时间后断开连接,我们 ...

随机推荐

  1. INT_MIN与溢出

    隔了好久没更新了,由于我在学习PL和编译器/解释器的知识. 挺好奇这方面的,由于没有学过相关的课程.所以学起来有点吃力,进展缓慢.所以导致没啥可写的. 今天看到这么一段话: 32位的int型的取值是2 ...

  2. Javascript中的DOM实现显示鼠标的空间位置

    为了显示鼠标相对于浏览器的位置(相对于屏幕和页面类似),我们能够利用click事件,获得关于鼠标单击的事件对象event.这个事件对象里的clientX和clientY包括了鼠标的位置信息,所以我突发 ...

  3. 【u242】排名系统

    Time Limit: 1 second Memory Limit: 64 MB [问题描述] F1的影响力越来越大,因此国际汽联决定扩大规模,让更多有天赋的车手加入这一行列. 不过规模的扩大带来了一 ...

  4. python2.x脚本转换为python3.x脚本的方法

    版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/dushu990/article/details/73549174 python2.x脚本转换为pyt ...

  5. Video processing systems and methods

    BACKGROUND The present invention relates to video processing systems. Advances in imaging technology ...

  6. unix shell(壳)的简单实现

    用户程序通过调用操作系统提供的系统调用(system call)API 来获得操作系统提供的各种服务.但使用 API 需要手动编写程序.对于不编程序.且需要与操作系统进行交互的用户,又如何使用操作系统 ...

  7. HDU 4313 Matrix 树形dp

    题意: 给定n个点的树,m个黑点 以下n-1行给出边和删除这条边的费用 以下m个黑点的点标[0,n-1] 删除一些边使得随意2个黑点都不连通. 问删除的最小花费. 思路: 树形dp 每一个点有2个状态 ...

  8. 寄存器,cache、伙伴系统、内存碎片、段式页式存储管理

    cache.伙伴系统.内存碎片.段式页式存储管理 目录 分层的存储管理 cache 局部性原理 置换算法 写回策略 linux环境下的cache 连续内存分配与内存碎片 内部碎片与外部碎片 动态分区分 ...

  9. 【struts2+hibernate4】小型电子商务站点

    这里使用的是struts2和hibernate4两个框架开发的一个小型电子商务站点,数据库方面我也会给出对应的代码. 总之使用的是:struts2+hibernate4+jsp+MySQL+tomca ...

  10. Managing remote devices

    A method and apparatus for managing remote devices. In one embodiment of the present invention, ther ...