gpt4 book ai didi

c# - NetworkStream.ReadAsync 的 ReadTimeout

转载 作者:行者123 更新时间:2023-12-03 11:52:48 28 4
gpt4 key购买 nike

NetworkStream.ReadAsync 什么时候任务完成?一旦接收到指定长度的数据?

如果是,它会返回 0 吗?然后 CancellationToken可以用作 ReadTimeout ,这是仅可用于同步操作的属性,对吧?

最佳答案

ReadAsync() 将永远自行“超时”。如果要取消它,请使用 CancellationToken。如果底层套接字关闭,ReadAsync() 将立即返回 0。

ReadAsync 一旦有数据就会返回,这可能是 1 个字节。它不会等到缓冲区已满。

    static async Task StartTcpClientAsync(TcpClient tcpClient)
{
Console.WriteLine($"Connection from: [{tcpClient.Client.RemoteEndPoint}]");

var stream = tcpClient.GetStream();
var buffer = new byte[1024];

while (true)
{
int x = await stream.ReadAsync(buffer, 0, 1024);
Console.WriteLine($"[{tcpClient.Client.RemoteEndPoint}] _ " +
$"read {x} bytes {System.Text.Encoding.UTF8.GetString(buffer)}");
}
}
static async Task StartTcpServerAsync()
{
var tcpListener = new TcpListener(new IPEndPoint(IPAddress.Any, 9999));
tcpListener.Start();
while (true)
{
var tcpClient = await tcpListener.AcceptTcpClientAsync();
_ = StartTcpClientAsync(tcpClient);
}
}
static async Task Main(string[] args)
{
_ = StartTcpServerAsync();
await Task.Delay(2000);
await RunSenderAsync();
}
static async Task RunSenderAsync()
{
var tcpClient = new TcpClient("127.0.0.1", 9999);
var s = tcpClient.GetStream();
tcpClient.NoDelay = true;
for (var i = 65; i < 91; i++)
{
s.Write(BitConverter.GetBytes(i), 0, 1);
await Task.Delay(1000);
}
}

产生:

[127.0.0.1:65201] read 1 bytes A
[127.0.0.1:65201] read 1 bytes B
[127.0.0.1:65201] read 1 bytes C
[127.0.0.1:65201] read 1 bytes D
[127.0.0.1:65201] read 1 bytes E
[127.0.0.1:65201] read 1 bytes F
...

关于c# - NetworkStream.ReadAsync 的 ReadTimeout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59351677/

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