gpt4 book ai didi

c# - 为什么配置 NetworkStream 会断开客户端

转载 作者:行者123 更新时间:2023-11-30 20:19:03 26 4
gpt4 key购买 nike

当以下基本代码正在发送或接收数据时,客户端会断开连接。

据我了解,using block 处理它创建的对象,即 NetworkStream 对象,但为什么 TcpClient Socket 会断开连接?

控制台输出是...真的错误

class Program
{
static void Main(string[] args)
{
Console.Title = "Client";

Process p = Process.Start(@"C:\Users\Teddy\Documents\visual studio 2015\code\TesyingNetworkStream\Server\bin\Debug\server.exe");
Thread.Sleep(1000);

IPEndPoint EP = new IPEndPoint(
IPAddress.Parse("192.168.1.10"), 4000
);

TcpClient cli = new TcpClient();
cli.Connect(EP);

UseClient(cli);

Console.ReadLine();
p.Kill();
p.Close();
}

private static void UseClient(TcpClient cli)
{
using (NetworkStream ns = cli.GetStream())
{
Console.WriteLine(cli.Connected);//True
}
Console.WriteLine(cli.Connected);//False
}
}

如果重要,这里是服务器代码。

class Program2
{
static void Main(string[] args)
{
Console.Title = "Server";

TcpListener lis = new TcpListener(
new IPEndPoint(
IPAddress.Any, 4000
));

lis.Start();

lis.AcceptTcpClient();

while (true)
{
Thread.Sleep(10);
}
}
}

最佳答案

这是 GetStream() 函数的实现(来自 .NET framework source ):

public NetworkStream GetStream() {
if (m_CleanedUp){
throw new ObjectDisposedException(this.GetType().FullName);
}
if (!Client.Connected) {
throw new InvalidOperationException(SR.GetString(SR.net_notconnected));
}
if (m_DataStream == null) {
m_DataStream = new NetworkStream(Client, true);
}
return m_DataStream;
}

注意 true 调用 NetworkStream 构造函数。这是 ownsSocket 参数。来自 MSDN :

If the value of ownsSocket parameter is true, the NetworkStream takesownership of the underlying Socket, and calling the Close method alsocloses the underlying Socket.

NetworkStreamDispose 实现Close 的流,然后关闭套接字。

关于c# - 为什么配置 NetworkStream 会断开客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39548233/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com