C#SocketException没有被捕获

l.m*_*tto 6 c# try-catch socketexception

我的代码中有一个非常奇怪的引用.我正在开发ac#chat客户端 - 服务器应用程序.当我关闭服务器时,我希望客户端自动关闭.客户端使用StremReader从TcpClient对象读取.客户端处于while循环中,它读取一行(StreamReader.ReadLine()),然后对其读取的行执行一些操作.当serever关闭时,我也关闭了tcp连接服务器端.所以,我期待客户端看到由readline引起的SocketException,捕获它并退出.但是例外不会被抓住!这是客户端循环代码:

 while (true)
 {
     try
     {
          ricev = read.ReadLine();
     }
     catch(SocketException exc)
     {
         //It never gets in here
     }
     chat.Invoke(showMessage, ricev);
 }
Run Code Online (Sandbox Code Playgroud)

当我关闭服务器时,visual studio告诉我在System.dll中引发了"System.Net.Sockets.SocketException"第一次机会异常,但我无法理解它.为什么会这样?我还尝试用a捕获任何一般异常

catch
{
}
Run Code Online (Sandbox Code Playgroud)

阻止,但这也不起作用.

任何帮助将不胜感激!

编辑:经过多次尝试后,我发现SocketException根本没有被提升.这是如此奇怪,正如我在评论中所说,在相反的情况下,当客户端在服务器之前关闭时,异常会被提升并且我可以解决它.我真的不知道发生了什么......

Jal*_*aid 1

如果我很理解你的情况,那么当你调用对象“ ”Stop的方法时,在流上调用时它不会抛出在客户端......我不知道为什么会发生这种情况,但我有一个围绕它的工作基础。它是通过访问底层并调用它来实现的:TcpListener_server.Stop()SocketExceptionReadSocketTcpListenerShutdown

_server.Stop();
_server.Server.Shutdown(SocketShutdown.Both);//now at your "read.ReadLine();" will throw SocketException
Run Code Online (Sandbox Code Playgroud)

编辑:您在评论中指出:

实际上我正在关闭accept方法上的监听器返回的tcpclient。connClient.Close()

如果停止tcpListerner_server.Stop()”,然后关闭clients_server.AcceptTcpCleint()方法中获取的内容,那么我会随意reader.ReadLine()抛出IOException: Unable to read data from the transport connection: A blocking operation was interrupted by a call to WSACancelBlockingCall 我自己测试的。