Socket.Listen Method

Defines the maximum number of pending connections that can be queued on the socket. This method prepares a Socket to accept incoming connection requests.

Syntax

public void Listen(int backlog);

Parameters

Exceptions

Remarks

Notes

The Listen method is used on a connection-oriented Socket to prepare it to accept incoming connection requests. You must call Bind before calling Listen.

The backlog parameter specifies the maximum length of the queue of pending connections. If the queue is full when a connection request arrives, the server may reject the request.

After calling Listen, you can accept incoming connection requests by calling the Accept method.

Example

Example Usage

The following example demonstrates how to use the Listen method to prepare a socket for incoming connections.

using System; using System.Net; using System.Net.Sockets; using System.Text; public class SimpleServer { public static void Main(string[] args) { // Create a TCP/IP socket. Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Bind the socket to the local endpoint and listen on the specified port. try { IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 11000); listener.Bind(localEndPoint); // Start listening for incoming connections. // Maximum of 10 pending connections in the queue. listener.Listen(10); Console.WriteLine("Waiting for a connection..."); Socket handler = listener.Accept(); // Program is suspended while waiting for connection Console.WriteLine("Client connected!"); // ... further processing ... handler.Close(); listener.Close(); } catch (Exception e) { Console.WriteLine(e.ToString()); } finally { if (listener != null) { listener.Dispose(); } } } }

Return Value

None.