Async TCP Client

suggest change

async/await keeps the calling thread free while socket I/O is in progress. This is how to use it with TcpClient. GetStream throws if it is called before the client is connected, so connect first.

// 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())
{
    // Asynchronously attempt to connect to the server
    await client.ConnectAsync(host, port);

    using (var netstream = client.GetStream())
    using (var writer = new StreamWriter(netstream))
    using (var reader = new StreamReader(netstream))
    {
        // AutoFlush the StreamWriter so we don't fill the buffer
        writer.AutoFlush = true;

        // ReadTimeout applies to synchronous reads, not to ReadLineAsync
        netstream.ReadTimeout = timeout;

        // Write a message over the TCP connection
        string message = "Hello World!";
        await writer.WriteLineAsync(message);

        // Read the server response
        string response = await reader.ReadLineAsync();
        Console.WriteLine($"Server: {response}");
    }
}
// The client and stream close when control leaves the using blocks
// (equivalent to, but safer than, calling Close())

Feedback about page:

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



Table Of Contents