SocketListener Class
Namespace: System.Net.Sockets
Provides a managed implementation of the Socket class for use with the Socket API.
Inheritance
- System.Object
- System.Net.Sockets.Socket
- System.Net.Sockets.SocketListener
Constructors
-
SocketListener(AddressFamily, SocketType, ProtocolType)
Initializes a new instance of the
SocketListenerclass.Parameters
- addressFamily
- The AddressFamily to use. For example,
AddressFamily.InterNetworkfor IPv4 orAddressFamily.InterNetworkV6for IPv6. - socketType
- The SocketType to use. For example,
SocketType.Streamfor a stream-based socket orSocketType.Dgramfor a datagram-based socket. - protocolType
- The ProtocolType to use. For example,
ProtocolType.TcporProtocolType.Udp.
Methods
-
Start()
Starts listening for incoming connections.
This method begins the process of accepting connections on the socket. The socket must be bound to an address and port before calling this method.
-
Stop()
Stops listening for incoming connections.
This method closes the socket and releases any resources associated with it, stopping all ongoing communication.
-
AcceptConnection() : Socket
Accepts an incoming connection.
This method blocks until a connection is made and returns a new
Socketobject representing the connection. It is typically used with stream-based sockets (e.g., TCP).Returns
- A
Socketobject representing the accepted connection. - A
-
BeginAccept(AsyncCallback, Object) : IAsyncResult
Begins an asynchronous operation to accept an incoming connection.
This method allows your application to continue execution while waiting for a connection. The
AsyncCallbackdelegate is invoked when the operation completes.Parameters
- callback
- An AsyncCallback delegate that references the method to call when the operation completes. Specify
nullto indicate that the application will handle completion by calling theEndAcceptmethod. - state
- A user-defined object that contains contextual information about the operation. This parameter can be
null.
Returns
- An IAsyncResult object that represents the asynchronous operation.
-
EndAccept(IAsyncResult) : Socket
Ends a pending asynchronous accept operation.
This method completes an asynchronous operation to accept a connection that was previously initiated by calling
BeginAccept.Parameters
- asyncResult
- An IAsyncResult object returned by a call to
BeginAccept.
Returns
- A
Socketobject representing the accepted connection.
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.");
}
}
}