Network Documentation FAQ

What is the .NET Network Stack?

The .NET network stack refers to the set of classes and APIs provided by the .NET Framework and .NET Core (now just .NET) for network communication. This includes support for various protocols like TCP, UDP, HTTP, and FTP, as well as higher-level abstractions for web services and client-server applications.

How do I make an HTTP request in .NET?

You can make HTTP requests using the HttpClient class, which is part of the System.Net.Http namespace. It's recommended to reuse a single instance of HttpClient for the lifetime of your application.

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

public class HttpExample
{
    public static async Task MakeRequestAsync()
    {
        using (HttpClient client = new HttpClient())
        {
            try
            {
                HttpResponseMessage response = await client.GetAsync("https://www.example.com");
                response.EnsureSuccessStatusCode(); // Throw an exception if the status code is not 2xx
                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseBody);
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine($"Request error: {e.Message}");
            }
        }
    }
}
                    

What is the difference between TCP and UDP?

TCP (Transmission Control Protocol) is a connection-oriented protocol that provides reliable, ordered, and error-checked delivery of a stream of bytes. It establishes a connection before sending data and ensures that all data arrives in the correct order. This makes it suitable for applications where data integrity is critical, such as web browsing or file transfer. UDP (User Datagram Protocol) is a connectionless protocol that provides a simpler, faster, but less reliable way to send messages. It does not establish a connection, does not guarantee delivery, and does not ensure the order of packets. UDP is suitable for applications where speed is more important than absolute reliability, such as streaming media or online gaming.

How do I listen for incoming TCP connections?

You can use the TcpListener class from the System.Net.Sockets namespace to create a server that listens for incoming TCP connections on a specific IP address and port.

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

public class TcpServer
{
    public static void StartListening()
    {
        int port = 13000;
        IPAddress localAddr = IPAddress.Parse("127.0.0.1");
        TcpListener server = new TcpListener(localAddr, port);

        server.Start();
        Console.WriteLine($"Listening on port {port}...");

        while (true)
        {
            Console.WriteLine("Waiting for a connection...");
            TcpClient client = server.AcceptTcpClient();
            Console.WriteLine("Client connected!");

            // Handle the client connection in a separate thread or task
            ThreadPool.QueueUserWorkItem(HandleClient, client);
        }
    }

    public static void HandleClient(object obj)
    {
        TcpClient client = (TcpClient)obj;
        NetworkStream stream = client.GetStream();
        byte[] bytes = new byte[1024];
        string data = null;

        try
        {
            int i = stream.Read(bytes, 0, bytes.Length);
            data = Encoding.ASCII.GetString(bytes, 0, i);
            Console.WriteLine($"Received: {data}");

            data = "Hello from server!";
            byte[] msg = Encoding.ASCII.GetBytes(data);
            stream.Write(msg, 0, msg.Length);
            Console.WriteLine($"Sent: {data}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error handling client: {ex.Message}");
        }
        finally
        {
            client.Close();
        }
    }
}
                    

What is TLS/SSL and how is it used in .NET?

TLS (Transport Layer Security) and its predecessor SSL (Secure Sockets Layer) are cryptographic protocols designed to provide communications security over a computer network. They are commonly used to encrypt the connection between a client and a server, ensuring privacy and data integrity. In .NET, you can enable TLS/SSL for various network protocols. For HTTP, HttpClient automatically uses HTTPS when the URL specifies it. For lower-level socket programming, you can use the SslStream class to wrap an existing stream (like a NetworkStream) and add TLS/SSL encryption.

How can I send and receive data over UDP?

You can use the UdpClient class from the System.Net.Sockets namespace to send and receive UDP datagrams.

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

public class UdpExample
{
    public static void SendMessage(string ipAddress, int port, string message)
    {
        using (UdpClient client = new UdpClient())
        {
            IPEndPoint ep = new IPEndPoint(IPAddress.Parse(ipAddress), port);
            byte[] messageBytes = Encoding.UTF8.GetBytes(message);
            client.Send(messageBytes, messageBytes.Length, ep);
            Console.WriteLine($"Sent UDP message: {message} to {ipAddress}:{port}");
        }
    }

    public static void ReceiveMessage(int port)
    {
        using (UdpClient client = new UdpClient(port))
        {
            Console.WriteLine($"Listening for UDP on port {port}...");
            IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
            byte[] receivedBytes = client.Receive(ref anyIP);
            string receivedMessage = Encoding.UTF8.GetString(receivedBytes);
            Console.WriteLine($"Received UDP message from {anyIP}: {receivedMessage}");
        }
    }
}