Search code examples
c#asynchronoustcpclient

C# encapsulation when getting updates from asynchronous method


I have a tcp connection I want to keep open in the HandleConnectionAsync method of the server class. It will be receiving continuous updates from a client.

private async void HandleConnectionAsync(TcpClient tcpClient)
    {
        Console.WriteLine("Got connection request from {0}", tcpClient.Client.RemoteEndPoint.ToString());
        try
        {
            using (var networkStream = tcpClient.GetStream())
            using (var reader = new StreamReader(networkStream))
            using (var writer = new StreamWriter(networkStream))
            {
                writer.AutoFlush = true;
                while (true)
                {
                    string dataFromClient = await reader.ReadLineAsync();
                    Console.WriteLine(dataFromClient);

                    await writer.WriteLineAsync("FromServer-" + dataFromClient);
                }
            }
        }
        catch (Exception exp)
        {
            Console.WriteLine(exp.Message);
        }
    }

I want to be able to receive the updates the reader puts into dataFromClient without having to put my code in the midst of my server implementation class. So:

static void Main(string[] args)
{
    Server s = new Server();
    s.start();
    //get dataFromClient as it comes in here
}

Problem is I'm not sure how to do this. Some kind of callback or event?


Solution

  • There are many many ways.

    The least code is to pass an Action to your server eg:

    Server s = new Server();
    s.start(dataFromClient => 
    {
        // do something with data from client
    });
    

    And in HandleConnectionAsync call the action eg:

    private async void HandleConnectionAsync(TcpClient tcpClient, Action<string> callback)
    {
        ..
        // Console.WriteLine(dataFromClient);
        callback(dataFromClient);
        ..
    

    However this does not address a few things e.g. many clients at the same time and needing to know which client is which.