TED*_*SON 4 c# using networkstream disconnect
当以下裸机代码正在发送或接收数据时,客户端会断开连接。
我的理解是 using 块处理它创建的对象,即 NetworkStream 对象,但为什么 TcpClient Socket 断开连接?
控制台输出是... True False
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
}
}
Run Code Online (Sandbox Code Playgroud)
如果重要,这里是服务器代码。
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是GetStream()函数实现(来自.NET 框架源):
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;
}
Run Code Online (Sandbox Code Playgroud)
请注意true对NetworkStream构造函数的调用中的。这是ownsSocket参数。从MSDN:
如果
ownsSocket参数的值为true,则 NetworkStream 获得底层 Socket 的所有权,调用该Close方法也会关闭底层 Socket。
NetworkStream的Dispose实现Close是流,然后关闭套接字。
| 归档时间: |
|
| 查看次数: |
904 次 |
| 最近记录: |