Networking Tasks in .NET

This section provides guidance and examples for common networking tasks using the .NET platform. .NET offers a rich set of classes for building networked applications, from simple client-server communication to complex web services.

Core Networking Concepts

Understanding the fundamental concepts is crucial for effective network programming:

Common Networking Tasks

Making HTTP Requests

The HttpClient class is the modern and recommended way to send HTTP requests.

using System;
using System.Net.Http;
using System.Threading.Tasks;

public class HttpExample
{
    public static async Task MakeRequestAsync(string url)
    {
        using (HttpClient client = new HttpClient())
        {
            try
            {
                HttpResponseMessage response = await client.GetAsync(url);
                response.EnsureSuccessStatusCode(); // Throw if HTTP status is 4xx or 5xx
                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseBody);
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine($"Request error: {e.Message}");
            }
        }
    }
}

TCP Socket Programming

For lower-level control, you can use the Socket class.

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class TcpServer
{
    public void StartServer(int port)
    {
        TcpListener listener = new TcpListener(IPAddress.Any, port);
        listener.Start();
        Console.WriteLine($"Server started on port {port}. Waiting for connections...");

        while (true)
        {
            TcpClient client = listener.AcceptTcpClient();
            Console.WriteLine("Client connected!");

            NetworkStream stream = client.GetStream();
            // Handle client communication...

            client.Close();
            Console.WriteLine("Client disconnected.");
        }
    }
}

UDP Communication

UDP is suitable for scenarios where performance is critical and some data loss is acceptable.

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class UdpClientExample
{
    public void SendData(string ipAddress, int port, string message)
    {
        using (UdpClient client = new UdpClient())
        {
            byte[] data = Encoding.UTF8.GetBytes(message);
            IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse(ipAddress), port);
            client.Send(data, data.Length, endpoint);
            Console.WriteLine($"Sent: {message}");
        }
    }
}

Important Note

When dealing with network security, always ensure proper authentication, authorization, and data encryption (e.g., using TLS/SSL).

Further Reading