System.Net.Sockets Namespace

Namespace: System.Net.Sockets

Provides low-level classes for network communication using sockets. This namespace contains classes that enable you to send and receive data across networks using various protocols, including TCP and UDP.

Key Classes

Socket Class

The Socket class provides the fundamental functionality for sending and receiving data using the socket API. It allows for flexible network programming, supporting both connection-oriented (like TCP) and connectionless (like UDP) protocols.

Properties

Properties
Name Description
Available Gets the number of bytes of data available to be read from the network buffer.
Blocking Gets or sets a value indicating whether the Socket is in blocking mode.
Connected Gets a value indicating whether the Socket is connected to a remote host.
Handle Gets the native socket handle.
IsBound Gets a value indicating whether the Socket is bound to a local endpoint.
LocalEndPoint Gets the local endpoint to which the Socket is bound.
ProtocolType Gets the protocol type of the Socket.

Methods

Methods
Name Description
Bind(EndPoint localEP) Binds the Socket to a local endpoint.
Connect(EndPoint remoteEP) Establishes a connection to a remote host.
Listen(int backlog) Puts a listening Socket into a listening state.
Accept() Accepts an incoming connection attempt and creates a new Socket to handle remote host communication.
Send(byte[] buffer) Sends the entire buffer containing data to the remote host.
Receive(byte[] buffer) Receives data from the network into the specified buffer.
Close() Releases all resources used by the Socket.
Note: The Socket class is powerful but can be complex to use directly. For many common networking scenarios, higher-level classes like TcpClient and UdpClient offer a simpler abstraction.

TcpClient Class

Provides a client side of a TCP service. This class simplifies the implementation of network-aware applications by providing a managed wrapper around the Socket class for TCP connections.

Key Features
  • Establishes TCP connections to remote hosts.
  • Provides access to the underlying Socket for advanced control.
  • Offers GetStream() to get a NetworkStream for sending and receiving data.

UdpClient Class

Provides support for User Datagram Protocol (UDP) network services. This class simplifies sending and receiving UDP datagrams.

Key Features
  • Sends and receives UDP datagrams.
  • Does not require a connection to be established before sending data.
  • Useful for broadcasting or sending small amounts of data where reliability is not critical.

Common Use Cases

Example: Simple TCP Echo Client

This example demonstrates a basic TCP client that connects to a server and sends a message, then receives the echoed response.


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

public class SimpleTcpClient
{
    public static void Main(string[] args)
    {
        string serverIp = "127.0.0.1"; // Replace with your server's IP
        int port = 8080; // Replace with your server's port
        string messageToSend = "Hello, Server!";

        try
        {
            using (TcpClient client = new TcpClient(serverIp, port))
            {
                Console.WriteLine($"Connected to {serverIp}:{port}");

                NetworkStream stream = client.GetStream();

                // Send message
                byte[] dataToSend = Encoding.ASCII.GetBytes(messageToSend);
                stream.Write(dataToSend, 0, dataToSend.Length);
                Console.WriteLine($"Sent: {messageToSend}");

                // Receive response
                byte[] buffer = new byte[1024];
                int bytesRead = stream.Read(buffer, 0, buffer.Length);
                string responseData = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                Console.WriteLine($"Received: {responseData}");
            }
        }
        catch (Exception e)
        {
            Console.WriteLine($"Error: {e.Message}");
        }
        Console.WriteLine("Press Enter to exit.");
        Console.ReadLine();
    }
}
            
Tip: Always wrap network operations in try-catch blocks to handle potential network errors, connection issues, or timeouts gracefully.