出于好奇,我一直在查看数据包捕获代码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”之间是否会收到,但我不认为这应该是一个问题吗?
答案 0 :(得分:1)
为遇到它的人回答我自己的问题:我的问题是防火墙的无声阻塞。为程序添加例外(包括VS studio调试可执行文件,即MJSniff.vshost.exe)允许查看传入流量。经验告诉我:这并不总是代码!