Overview
The .NET networking stack provides a rich set of APIs for building reliable, high‑performance networked applications. From low‑level socket programming to high‑level HTTP clients, .NET abstracts the complexities of the underlying protocols.
Key Namespaces
System.Net– Core networking types such asWebClient,WebRequest, andDns.System.Net.Sockets– Low‑level socket APIs for TCP/UDP.System.Net.Http– Modern HTTP client and server abstractions.System.Net.WebSockets– Full‑duplex communication over WebSockets.
Example: Simple TCP Client
using System;
using System.Net.Sockets;
using System.Text;
class TcpEchoClient
{
static async Task Main()
{
using var client = new TcpClient();
await client.ConnectAsync("localhost", 5000);
NetworkStream stream = client.GetStream();
string message = "Hello, server!";
byte[] data = Encoding.UTF8.GetBytes(message);
await stream.WriteAsync(data, 0, data.Length);
var buffer = new byte[1024];
int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
string response = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine($"Received: {response}");
}
}
Example: HTTP GET with HttpClient
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
using var http = new HttpClient();
HttpResponseMessage resp = await http.GetAsync("https://api.github.com/repos/dotnet/runtime");
resp.EnsureSuccessStatusCode();
string json = await resp.Content.ReadAsStringAsync();
Console.WriteLine(json);
}
}
Best Practices
- Prefer
HttpClientover olderWebRequestAPIs. - Reuse
HttpClientinstances to avoid socket exhaustion. - Use async APIs to keep applications responsive.
- Validate certificates when using TLS.
- Handle transient failures with retry policies (e.g., Polly library).