读取Socket比数据到达更快

时间:2014-06-30 18:59:00

标签: c# sockets

以下是我在阅读Socket时使用的ResponseCallback的简化版本:

private void ResponseCallback(IAsyncResult ar)
{
    StateObject state = (StateObject)ar.AsyncState;
    Socket target = state.Target;

    int read = target.EndReceive(ar);
    state.Message.AddRange(state.Buffer.Take(read));

    //Console.WriteLine("read: " + read + "\ttarget.Available: " + target.Available);
    //Thread.Sleep(100);

    // If we still have data, keep receiving.
    if (target.Available > 0)
    {
        target.BeginReceive(state, ResponseCallback);
    }
    else
    {
        // Otherwise, we've received the full message; do other processing.
    }
}

如果我没有Thread.Sleep,我会从Console.WriteLine获得以下内容:

  

阅读:4096 target.Available:1344

     

阅读:1344 target.Available:0

使用Thread.Sleep,我得到以下内容:

  

阅读:4096 target.Available:1344

     

阅读:3100 target.Available:0

消息在没有Thread.Sleep的情况下被切断但完成了。我怎样才能确保收到完整的信息?我尝试过切换

if (target.Available > 0)

if (read > 0)

然而,BeginReceive永远不会以0读取结束 - 这是有道理的,因为这意味着它没有收到任何东西,所以它不应该结束。

我做错了什么?

0 个答案:

没有答案