0

出于好奇,我一直在看这里的数据包捕获代码。有这样一段:

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”之间接收是否会丢失,但我认为这不应该是一个问题?

4

1 回答 1

1

为遇到它的任何人回答我自己的问题:我的问题是防火墙的无声阻塞。为程序添加例外(包括 VS studio 调试可执行文件,即 MJSniff.vshost.exe)允许查看传入流量。我学到的教训:它并不总是代码!

于 2012-12-11T03:35:14.547 回答