简体   繁体   English

C#NetworkStream不会引发异常

[英]C# NetworkStream wont throw exception

I am writing a simple C# server and client , but it doesn't throw an exception when the client is disconnected. 我正在编写一个简单的C#服务器和客户端 ,但是当客户端断开连接时,它不会引发异常。 It will continue reading from the client, thinking that the client is still there. 它将继续从客户端阅读,以为客户端仍在那儿。 It also no longer blocks when the client is gone. 当客户端消失时,它也不再阻塞。 I expect it to throw an exception if the client is no longer available. 如果客户端不再可用,我希望它会引发异常。

private TcpListener server;
private NetworkStream stream;
private TcpClient client;
private byte[] buffer = new byte[1];

server = new TcpListener (serverIp, _portNumber);
server.Start();

stream = client.GetStream();

//The part I want to throw exception when the client is gone but doesn't. //当客户端消失但我不想抛出异常时,我要抛出异常的部分。

try
{
    stream.Read(buffer,0,1);
}
catch(Exception e)
{
    #if (DEBUG)
    Debug.Log ("Failed Rading " + e.Message);
    #endif
    return 0; 
}

Any help would be appreciated. 任何帮助,将不胜感激。

It should throw an exception when the connection is closed and there is no more data in the buffer to read. 当连接关闭并且缓冲区中没有更多数据可读取时,它将引发异常。 Apparently there is still data available. 显然仍然有可用数据。 When the buffer and the connection is closed you should get an exception. 当缓冲区和连接关闭时,您应该得到一个异常。 Also I see you read data 1 byte at the time. 另外我看到您一次读取了1个字节的数据。 Why not first check if the connection is alive: 为什么不首先检查连接是否仍然有效:

client.Client.Poll(0, SelectMode.SelectRead)

check if there is data available to read and read the correct amount: 检查是否有可用于读取和读取正确数量的数据:

int available = client.Client.Available;
if(available > 0)
{
   var buffer = new byte[available];
   client.Read(buffer, 0, available);
}

If the client goes away without notifying the server there is nothing you can do except timeout. 如果客户端在没有通知服务器的情况下离开,则除了超时外您无能为力。 The server has no way of finding out the fact that the client is gone. 服务器无法找出客户端已消失的事实。

You need to live with this fact. 您需要忍受这个事实。 Set a timeout. 设置超时时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM