异步 TCP 客户端

在 C#应用程序中使用 async/await 简化了多线程。这就是你如何将 async/await 与 TcpClient 结合使用。

// Declare Variables
string host = "stackoverflow.com";
int port = 9999;
int timeout = 5000;

// Create TCP client and connect
// Then get the netstream and pass it
// To our StreamWriter and StreamReader
using (var client = new TcpClient())
using (var netstream = client.GetStream()) 
using (var writer = new StreamWriter(netstream))
using (var reader = new StreamReader(netstream))
{
    // Asynchronsly attempt to connect to server
    await client.ConnectAsync(host, port);
    
    // AutoFlush the StreamWriter
    // so we don't go over the buffer
    writer.AutoFlush = true;
    
    // Optionally set a timeout
    netstream.ReadTimeout = timeout;

    // Write a message over the TCP Connection
    string message = "Hello World!";
    await writer.WriteLineAsync(message);
    
    // Read server response
    string response = await reader.ReadLineAsync();
    Console.WriteLine(string.Format($"Server: {response}"));                
}
// The client and stream will close as control exits
// the using block (Equivilent but safer than calling Close();