【发布时间】:2017-01-25 16:06:36
【问题描述】:
当以下基本代码发送或接收数据时,客户端断开连接。
我的理解是 using 块会释放它创建的对象,即 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);
}
}
}
【问题讨论】:
标签: c# using networkstream disconnect