NetworkStream.ReadAsync 的读取超时

ReadTimeout for NetworkStream.ReadAsync

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

如果是,它曾经 return 0 吗?然后是CancellationToken could be used as the ReadTimeout,因为属性只能用于同步操作,对吧?

ReadAsync() 将永远 "time out" 自己。如果要取消它,请使用 CancellationToken。如果底层套接字关闭,ReadAsync() 将 return 立即为 0。

ReadAsync 将 return 一旦有数据,这可能是 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
...