1
votes

MSDN says about the Socket.Listen method:

Listen causes a... Socket to listen for incoming connection attempts. The backlog parameter specifies the number of incoming connections that can be queued for acceptance... Use Accept or BeginAccept to accept a connection from the queue.

This implies that the socket will put incoming connections into a queue. How do we determine the number of queued connections?

var localEndPoint = new IPEndPoint(IPAddress.Any, Port);

var serverSocket = new Socket(
    AddressFamily.InterNetwork,
    SocketType.Stream,
    ProtocolType.Tcp);

serverSocket.Bind(localEndPoint);

// listen for incoming connections; queue `socketBacklog` of them
// Listen bit.ly/21vz22b
serverSocket.Listen(socketBacklog);

// how do we do this?
serverSocket.CountQueuedConnections()

One thing I have tried, which clearly does not work, is serverSocket.Poll(timeToWait, SelectMode.SelectRead). This always returns false.

1

1 Answers

2
votes

Taking an example from MSDN's Socket Code Examples :

Asynchronous Server Socket Example

 Socket listener = new Socket(AddressFamily.InterNetwork,
        SocketType.Stream, ProtocolType.Tcp );

    // Bind the socket to the local endpoint and listen for incoming connections.
    try {
        listener.Bind(localEndPoint);
        listener.Listen(100);

        while (true) {
            // Set the event to nonsignaled state.
            allDone.Reset();

            // Start an asynchronous socket to listen for connections.
            Console.WriteLine("Waiting for a connection...");
            listener.BeginAccept( 
                new AsyncCallback(AcceptCallback),
                listener );

            // Wait until a connection is made before continuing.
            allDone.WaitOne();
        }

    } catch (Exception e) {
        Console.WriteLine(e.ToString());
    }

In this code, you can easily add a counter inside the infinite-loop to determine how many clients have connected to the server.

Socket.Listen Method (Int32) only provides the maximum number of clients which can connect to this ServerSocket. Also, Listen does not block.