You can get the NetworkStream from a TcpClient with client.GetStream() and pass it into a StreamReader/StreamWriter to gain access to their async read and write methods.
Async TCP Client
Using async/await in C# applications simplifies multi-threading. This is how you can use async/await in conjunction with a TcpClient.
Basic TCP Communication Client
This code example creates a TCP client, sends "Hello World" over the socket connection, and then writes the server response to the console before closing the connection.
Basic UDP Client
This code example creates a UDP client then sends "Hello World" across the network to the intended recipient. A listener does not have to be active, as UDP Is connectionless and will broadcast the message regardless. Once the message is sent, the clients work is done.
Below is an example of a UDP listener to complement the above client. It will constantly sit and listen for traffic on a given port and simply write that data to the console. This example contains a control flag 'done' that is not set internally and relies on something to set this to allow for ending the listener and exiting.
Download a file from a web server
Downloading a file from the internet is a very common task required by almost every application your likely to build.
The simplest use of this, using the "using" pattern, is shown below:
What this example does is it uses "using" to make sure that your web client is cleaned up correctly when finished, and simply transfers the named resource from the URL in the first parameter, to the named file on your local hard drive in the second parameter.
You can also use this function is an async form, so that it goes off and performs the download in the background, while your application get's on with something else, using the call in this way is of major importance in modern applications, as it helps to keep your user interface responsive.
When you use the Async methods, you can hook up event handlers that allow you to monitor the progress, so that you could for example, update a progress bar, something like the following:
One important point to remember if you use the Async versions however, and that's "Be very carefull about using them in a 'using' syntax".
The reason for this is quite simple. Once you call the download file method, it will return immediately. If you have this in a using block, you will return then exit that block, and immediately dispose the class object, and thus cancel your download in progress.
If you use the 'using' way of performing an Async transfer, then be sure to stay inside the enclosing block until the transfer completes.
This modified text is an extract of the original Stack Overflow Documentation created by following contributors and released under CC BY-SA 3.0