非同步 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();