【发布时间】:2012-04-13 01:46:37
【问题描述】:
出于好奇,我一直在查看数据包捕获代码here。有这样一段:
private void OnReceive(IAsyncResult ar)
{
try
{
int nReceived = mainSocket.EndReceive(ar);
//Analyze the bytes received...
ParseData (byteData, nReceived);
if (bContinueCapturing)
{
byteData = new byte[4096];
//Another call to BeginReceive so that we continue to receive the incoming
/packets
mainSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None,
new AsyncCallback(OnReceive), null);
}
}
...
...
}
MSDN 文档说 EndReceive 确实返回接收到的字节数,但是在每次异步接收之后简单地连续添加 nReceived 并不会接近我预期的字节数。例如,下载一个 16 MB 的文件只达到大约 200K。
我查看了与此类似的其他问题,但没有找到任何东西。我尝试改变缓冲区大小以查看是否有所不同,但没有。我只是误解了代码的作用吗?
编辑:接收到的字节是这样累积的。看起来很简单,所以希望我没有弄错!
long totalBytes = 0;
Object byteLock = new Object();
private void ParseData(byte[] byteData, int nReceived)
{
lock (byteLock)
{
totalBytes += nReceived;
}
}
Edit2:这里是用来接收数据的代码。如果需要更多详细信息,可以从我的问题开头的链接获得完整的源代码。该文件是 MJsnifferForm.cs。
private void OnReceive(IAsyncResult ar)
{
try
{
int nReceived = mainSocket.EndReceive(ar);
//Analyze the bytes received...
ParseData (byteData, nReceived);
if (bContinueCapturing)
{
byteData = new byte[4096];
//Another call to BeginReceive so that we continue to receive the incoming
//packets
mainSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None,
new AsyncCallback(OnReceive), null);
}
}
catch (ObjectDisposedException)
{
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "MJsniffer", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
我想知道在调用“mainSocket.EndReceive”和下一次调用“mainSocket.BeginReceive”之间接收是否会丢失,但我认为这不应该是一个问题?
【问题讨论】:
-
我很惊讶地发现下载 16 MB 会导致总字节数小于 200K。当然,假设整个文件都已下载。您是如何将收到的字节数相加的?
-
我只是添加了一个小计数器并累积了传递给 ParseData 例程的内容。在上面添加了一个示例。
-
你能显示你调用 EndReceive 的代码吗?您什么时候停止接收?
-
当然,在我的问题中添加了更多内容。
标签: .net sockets beginreceive