gpt4 book ai didi

c# - async await 与 TcpClient 的用法

转载 作者:可可西里 更新时间:2023-11-01 02:32:05 25 4
gpt4 key购买 nike

我最近开始使用新的 C#5.0“async”和“await”关键字。我以为我明白了,但意识到一件事让我怀疑。下面是我如何从远程 TcpClient 异步接收数据。接受连接后,我调用此函数:

static async void ReadAsync(TcpClient client)
{
NetworkStream ns = client.GetStream();
MemoryStream ms = new MemoryStream();
byte[] buffer = new byte[1024];

while(client.Connected)
{
int bytesRead = await ns.ReadAsync(buffer, 0, buffer.Length);
ms.Write(buffer, 0, bytesRead);
if (!ns.DataAvailable)
{
HandleMessage(ms.ToArray());
ms.Seek(0, SeekOrigin.Begin);
}
}
}

接收到数据后,循环继续下去,不读取任何内容。我在循环中使用 Console.WriteLine 对此进行了测试。我使用正确吗?我觉得我不应该使用 while 循环...

最佳答案

TcpClient.Connected 值不会立即更新。根据 MSDN:

true if the Client socket was connected to a remote resource as of the most recent operation; otherwise, false.

因此将 TcpClient.Connected 作为 while 循环条件并不是一个好的选择。

TcpClient.DataAvailable用于同步操作,不用于异步。

将您的代码更新为:

static async void ReadAsync(TcpClient client)
{
NetworkStream ns = client.GetStream();
MemoryStream ms = new MemoryStream();
byte[] buffer = new byte[1024];

while(true) {
int bytesRead = await ns.ReadAsync(buffer, 0, buffer.Length);
if (bytesRead <= 0)
break;
ms.Write(buffer, 0, bytesRead);
HandleMessage(ms.ToArray());
ms.Seek(0, SeekOrigin.Begin);
}
}

ReadAsync返回0时,表示TCP连接关闭或关闭。在 MSDN 中:

The value of the TResult parameter contains the total number of bytes read into the buffer. The result value can be less than the number of bytes requested if the number of bytes currently available is less than the requested number, or it can be 0 (zero) if the end of the stream has been reached.

关于c# - async await 与 TcpClient 的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24111640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com