【发布时间】:2026-02-20 00:40:01
【问题描述】:
为什么我不能从 C# 中的 TcpClient 读取字节?
这是我得到的错误:
Unable to read data from the transport connection: An established connection was aborted by the software in your host machine.
这是我启动 TcpClient 的方式:
public static async void Start()
{
TcpListener server = null;
try
{
server = new TcpListener(IPAddress.Loopback, 13000);
server.Start();
var client = await server.AcceptTcpClientAsync();
var stream = client.GetStream();
var bytes = Convert.FromBase64String("ABCD");
await stream.WriteAsync(bytes, 0, bytes.Length);
client.Close();
}
catch (Exception e)
{
throw;
}
finally
{
if(server != null)
{
server.Stop();
}
}
}
这是我向 TcpClient 运行请求的方式:
try {
var response = (new HttpClient()).GetByteArrayAsync("http://localhost:13000").Result;
return Convert.ToBase64String(response);
} catch(Exception e) {
throw;
}
永远无法到达return Convert.ToBase64String(response); 行。如果我在throw 行上遇到断点,我会在Exception e 中看到上面引用的错误消息。
此外,在调试过程中,Start() 方法完成得很好。 IE。它开始,然后等待请求,获取请求,写入 TclClient,最后运行server.Stop(); 命令。
我希望我的代码能够正常工作,因为我从here 的官方文档中获取并修改了它。
我尝试查看一些可以解决我的异常的资源,但它们都没有帮助。
例如我尝试使用the 问题。
第一个答案实际上并没有说明什么有用的东西,只是在玩弄文字,最后说人们对异常无能为力(如果我在答案中遗漏了一点,请纠正我)。
第二个答案在我的案例中说明了一个不可能的问题。因为,我确信 13000 端口上没有运行任何东西。
【问题讨论】:
标签: sockets asp.net-core tcp tcpclient tcplistener