有一个异步服务器的代码。客户端发送 Header - Data Block + Data Block 的大小。
服务器首先异步读取 Header,然后读取 Data Block。
我需要在读取数据块后运行 BeginRead for Header 读取部分,以使线程异步。
问题:
当我得到 DataCallBack 时,排队:
int bytesRead = ns.EndRead(result);
我没有得到我要求读入的所有缓冲区
mc.Client.GetStream().BeginRead(mc.DataBuffer, 0, size, new AsyncCallback(DataCallBack), mc);
如果客户端发送 1MB 的数据,我可以获得不同数量的“bytesRead”。
问题:
如何强制“BeginRead”从连接中读取所有数据。它应该导致新的 Header - Data 循环。
MyClient - 简单地包装 TcpClient;
代码:
public void DoAcceptTcpClientCallback(IAsyncResult ar)
{
TcpListener listener = (TcpListener)ar.AsyncState;
TcpClient client = listener.EndAcceptTcpClient(ar);
client.NoDelay = false;
// client.ReceiveBufferSize = 1024*1024;
listener.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpClientCallback), listener);
MyClient mc = new MyClient(client);
ContinueRead(0,mc);
}
public void ContinueRead(int size, MyClient mc)
{
if (size != 0)
{
mc.DataBuffer = new byte[size];
mc.Client.GetStream().BeginRead(mc.DataBuffer, 0, size, new AsyncCallback(DataCallBack), mc);
}
mc.Client.GetStream().BeginRead(mc.HeaderBuffer, 0, 4, new AsyncCallback(HeaderCallBack), mc);
}
private void HeaderCallBack(IAsyncResult result)
{
MyClient mc = (MyClient)result.AsyncState;
NetworkStream ns = mc.Stream;
int bytesRead = ns.EndRead(result);
if (bytesRead == 0)
throw new Exception();
mc.TotalLengs = BitConverter.ToInt32(mc.HeaderBuffer, 0);
ContinueRead(mc.TotalLengs, mc);
}
private void DataCallBack(IAsyncResult result)
{
MyClient mc = (MyClient)result.AsyncState;
NetworkStream ns = mc.Stream;
int bytesRead = ns.EndRead(result);
if (bytesRead == 0)
throw new Exception();
错误的代码 - 使异步读取 - 同步
while (bytesRead < mc.TotalLengs)
{
bytesRead += ns.Read(mc.DataBuffer, bytesRead, mc.TotalLengs - bytesRead);
}
结束错误代码
ContinueRead(0, mc);
ProcessPacket(mc.DataBuffer, mc.IP);
}