从异步方法获取更新时的C#封装

时间:2017-10-20 09:57:04

标签: c# asynchronous tcpclient

我有一个tcp连接我想在服务器类的HandleConnectionAsync方法中保持打开状态。它将从客户端接收持续更新。

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);
        }
    }

我希望能够接收读者放入dataFromClient的更新,而无需将我的代码放在我的服务器实现类中。 所以:

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

问题是我不知道该怎么做。某种回调或事件?

1 个答案:

答案 0 :(得分:2)

有很多方法。

最少的代码是将Action传递给您的服务器,例如:

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

在HandleConnectionAsync中调用动作例如:

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

然而,这并没有解决一些问题,例如:许多客户同时需要知道哪个客户是哪个。