如何读取异步tcpclient网络流

时间:2019-04-11 20:16:09

标签: c# asynchronous tcpclient

我正在尝试使用TcpClient和TcpListener使用async制作聊天应用程序,并在c#中等待。

这是我想出的代码。问题在于,一旦客户端写入流,服务器似乎将无法读取

public class asyncClient    {
   public async static Task Start()    {
    TcpClient client = new TcpClient();
    await client.ConnectAsync(IPAddress.Parse("127.0.0.1"), 11000);

    String message = "hello world";
    NetworkStream ns =  client.GetStream();
    StreamWriter sw = new StreamWriter(ns);
    await sw.WriteLineAsync(message);



    }
public static void Main(){
    Start().Wait();
    }
}

这是侦听器代码

public class AsynchListener
{
public async static Task StartListening()
{
    TcpListener listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 
 11000);

    listener.Start();
    while (true) {
        TcpClient handler = await listener.AcceptTcpClientAsync();



        NetworkStream ns = handler.GetStream();
        StreamReader sr = new StreamReader(ns);
        String message = await sr.ReadLineAsync();

        Console.WriteLine(message);
    }
    Console.WriteLine("check");




}


    public static void Main(string[] args)
    {
    StartListening().Wait();
    }

 }

1 个答案:

答案 0 :(得分:0)

好的,我发现了错误,我不见了

await sw.FlushAsync();

在writeline命令之后