异步等待与 TcpClient 一起使用 [英] async await usage with TcpClient

查看:39
本文介绍了异步等待与 TcpClient 一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始使用新的 C#5.0async"和await"关键字.我以为我明白了,但意识到一件事让我怀疑.这是我从远程 TcpClient 异步接收数据的方式.一旦我接受连接,我就会调用这个函数:

I recently started using the new C#5.0 "async" and "await" keywords. I thought I got the twist but realized one thing that made me doubt. Here's how I was asynchronously receiving data from a remote TcpClient. Once I accept the connection I call this function :

static async void ReadAsync(TcpClient client)
{
    NetworkStream ns = client.GetStream();
    MemoryStream ms = new MemoryStream();
    byte[] buffer = new byte[1024];

    while(client.Connected)
    {
        int bytesRead = await ns.ReadAsync(buffer, 0, buffer.Length);
        ms.Write(buffer, 0, bytesRead);
        if (!ns.DataAvailable)
        {
            HandleMessage(ms.ToArray());
            ms.Seek(0, SeekOrigin.Begin);
        }
    }
}

接收到数据后,循环继续下去,没有读取任何内容.我在循环中使用 Console.WriteLine 对此进行了测试.我是否正确使用它?我觉得我不应该使用 while 循环...

After data is received, the loop just goes on and on without reading anything. I tested this with a Console.WriteLine in the loop. Am I using it correctly? I feel I should not be using a while loop...

推荐答案

我最终使用了长度为前缀的消息,在每个数据包前面加上 4 个字节的前缀,代表即将到来的数据的长度.

I ended up using length-prefixed messages, prefixing every packet by 4 bytes representing the length of the data to come.

这篇关于异步等待与 TcpClient 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆