Async TCP Client

suggest change

Using async/await in C# applications simplifies multi-threading. This is how you can use async/await in conjunction with a 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();

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Networking:
* Async TCP Client

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
46 Methods
88 Events
92 Structs
96 Networking
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script