【问题标题】:how to read an async tcpclient network stream [duplicate]如何读取异步 tcpclient 网络流 [重复]
【发布时间】:2019-04-11 20:16:09
【问题描述】:

我正在尝试使用 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();
    }

 }

【问题讨论】:

  • 请注意,您的问题与使用异步 API 完全无关,而只是错误地滥用了 text-writer API,如标记的重复项。

标签: c# asynchronous tcpclient


【解决方案1】:

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

await sw.FlushAsync();

在 writeline 命令之后

【讨论】:

    猜你喜欢
    • 2022-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-07
    • 1970-01-01
    相关资源
    最近更新 更多