c# - 如何读取异步 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();
}
}
解决方案
好的,我发现了错误,我错过了
await sw.FlushAsync();
在 writeline 命令之后
推荐阅读
- hybris - 如何在后台的创建向导中显示和处理“非模型”属性
- amazon-web-services - 我可以将子域直接指向 AWS 中的 API 端点吗?
- javascript - 如何使用 Javascript 从 json 返回 HTML?
- excel - 使用正则表达式识别评估字符串中匹配的捕获组
- vue.js - OKta + Vue :当从按钮调用或从 vue 页面创建事件调用时,Okta 注销代码的行为不同
- flutter - 未定义命名参数“形状”和“颜色”
- freeradius - 使用 NAS-Port 属性执行认证
- html - 使用 Vue 3 的 Vue 路由器引发 17 条警告,并且应用程序文件的内容不显示
- math - 如何为我的 CNN 计算数学公式?
- java - 遍历一个 Json 对象并将一些值存储在一个数组中