SocketListener Class

Namespace: System.Net.Sockets

Provides a managed implementation of the Socket class for use with the Socket API.

Inheritance

Constructors

Methods

Remarks

The SocketListener class is a higher-level abstraction over the Socket class, designed specifically for scenarios where a server application needs to listen for and accept incoming network connections. It simplifies the common pattern of binding, listening, and accepting connections, especially in conjunction with asynchronous operations.

This class is particularly useful for building TCP servers. For UDP-based applications, direct use of the Socket class might be more appropriate as UDP is connectionless.

Example


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

public class SimpleTcpServer
{
    public static void Main(string[] args)
    {
        int port = 13000;
        var listener = new SocketListener(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        try
        {
            listener.Bind(new IPEndPoint(IPAddress.Any, port));
            listener.Listen(10); // Listen for up to 10 pending connections

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

            while (true)
            {
                Console.WriteLine("Waiting for a connection...");
                Socket handler = listener.AcceptConnection(); // Synchronous accept
                Console.WriteLine("Connection accepted.");

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

                    string response = "Hello from server!";
                    byte[] responseBytes = Encoding.ASCII.GetBytes(response);
                    handler.Send(responseBytes);
                    Console.WriteLine("Response sent.");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error handling connection: {ex.Message}");
                }
                finally
                {
                    handler.Close(); // Close the connection socket
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Server error: {ex.Message}");
        }
        finally
        {
            listener.Close(); // Close the listener socket
            Console.WriteLine("Server stopped.");
        }
    }
}