.NET Documentation

System.Net.Sockets Namespace

The System.Net.Sockets namespace provides low-level access to the Windows Sockets API, enabling you to implement custom network protocols and client/server applications. This namespace is fundamental for building any application that requires network communication, from simple web requests to complex distributed systems.

Core Concepts

Key Classes

The following are some of the most important classes within the System.Net.Sockets namespace:

Common Use Cases

Getting Started

To begin, you'll typically create a Socket object, specify the address family (e.g., IPv4 or IPv6), socket type (e.g., stream for TCP or datagram for UDP), and protocol. You can then use methods like Bind, Listen, Accept, Connect, Send, and Receive to manage network communication.

Example: Basic TCP Server Setup


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

public class SimpleTcpServer
{
    public static void StartServer(int port)
    {
        IPAddress ipAddress = IPAddress.Any;
        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);

        Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

        try
        {
            listener.Bind(localEndPoint);
            listener.Listen(10); // Maximum of 10 pending connections

            Console.WriteLine($"Listening on {localEndPoint}...");

            while (true)
            {
                Socket handler = listener.Accept(); // Blocks until a client connects
                Console.WriteLine("Client connected.");

                byte[] bytes = new byte[1024];
                int bytesRec = handler.Receive(bytes);
                string data = Encoding.ASCII.GetString(bytes, 0, bytesRec);
                Console.WriteLine($"Received: {data}");

                // Echo back
                byte[] msg = Encoding.ASCII.GetBytes($"Echo: {data}");
                handler.Send(msg);
                Console.WriteLine($"Sent: Echo: {data}");

                handler.Shutdown(SocketShutdown.Both);
                handler.Close();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
        finally
        {
            listener.Close();
        }
    }

    // In a real application, you'd call this from Main() or another entry point.
    // public static void Main(string[] args) { StartServer(11000); }
}
            

This example demonstrates the fundamental steps: creating a listener socket, binding it to an address and port, listening for incoming connections, accepting a connection, receiving data, and sending a response back. For more advanced scenarios, consider using the higher-level TcpClient and UdpClient classes.