Socket.Listen Method
System.Net.Sockets.Socket.Listen
Syntax
public void Listen( int backlog )
Parameters
| Name | Description |
|---|---|
| backlog | The maximum length of the pending connections queue. |
Remarks
The Listen method enables a Socket to accept incoming connection requests.
The backlog parameter specifies the maximum number of pending connections that can be queued up before the system starts rejecting new connections. The actual maximum queue length can vary depending on the operating system.
After calling Listen, the Socket transitions to the listening state, and you can use the Accept method to establish connections with clients.
If you are using a connection-oriented Socket (such as SocketType.Stream with ProtocolType.Tcp), you must call Bind and then Listen before calling Accept.
If you are using a connectionless Socket (such as SocketType.Dgram with ProtocolType.Udp), you do not need to call Listen.
Examples
The following code example demonstrates how to set up a listening Socket.
// Requires using System.Net; // Requires using System.Net.Sockets; try { // Create a TCP/IP socket. Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Bind the socket to the local endpoint and listen for incoming connections. IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 11000); listener.Bind(ipEndPoint); listener.Listen(100); // Listen for up to 100 pending connections Console.WriteLine("Socket is listening on port 11000..."); // Now accept connections... Socket handler = listener.Accept(); // ... handle the connection ... handler.Shutdown(SocketShutdown.Both); handler.Close(); } catch (Exception e) { Console.WriteLine(e.ToString()); }
Requirements
| Interface | Value |
|---|---|
| Implemented in | System.Net.Sockets |
| Inherited from | System.Object |
| Assembly | System.Net.Sockets.dll |