以下是我在阅读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
读取结束 - 这是有道理的,因为这意味着它没有收到任何东西,所以它不应该结束。
我做错了什么?