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:



Table Of Contents