vtortola
vtortola

Reputation: 35885

Is correct this pattern for an asynchronous TCP listener?

I was wondering if I'm doing right in an application I'm building. The app has to receive incoming TCP connections, and use a thread per call, so the server can answer multiple calls in parallel.

What I'm doing is call BeginAcceptTcpClient again as soon I got an accepted client. I guess that when the ConnectionAccepted method is hit, it's actually in a separate thread.

public class ServerExample:IDisposable
{
    TcpListener _listener;
    public ServerExample()
    {
        _listener = new TcpListener(IPAddress.Any, 10034);
        _listener.Start();
        _listener.BeginAcceptTcpClient(ConnectionAccepted,null);
    }

    private void ConnectionAccepted(IAsyncResult ia)
    {
        _listener.BeginAcceptTcpClient(ConnectionAccepted, null);
        try
        {
            TcpClient client = _listener.EndAcceptTcpClient(ia);

            // work with your client
            // when this method ends, the poolthread is returned
            // to the pool.
        }
        catch (Exception ex)
        {
            // handle or rethrow the exception
        }
    }

    public void Dispose()
    {
        _listener.Stop();
    }
}

Am I doing right?

Cheers.

Upvotes: 4

Views: 1851

Answers (1)

Marino Šimić
Marino Šimić

Reputation: 7332

Well you could make the method static like this :

private static void ConnectionAccepted(IAsyncResult ia)
    {         
     var listener = (TcpListener)result.AsyncState;
     TcpClient client = listener.EndAcceptTcpClient();
     listener.BeginAcceptTcpClient(ConnectionAccepted, listener);
     // .....
     }

maybe you don't want it to be static but this way you could move the method where you like it and do not depend on member variables in this class but another one. I.E: decouple server tcp logic and server client logic.

Upvotes: 1

Related Questions