首页 > 解决方案 > 如何读取异步 tcpclient 网络流

问题描述

我正在尝试使用 TcpClient 和 TcpListener 在 c# 中使用 async 和 await 制作一个聊天应用程序。

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

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

 }

标签: c#asynchronoustcpclient

解决方案


好的,我发现了错误,我错过了

await sw.FlushAsync();

在 writeline 命令之后


推荐阅读