Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# SocketException doesn't get caught

i have a really weird sitation going on in my code. I'm developping a c# chat client-server application. When i close the server i want the client to be automatically closed. The client is reading from the TcpClient object using a StremReader. The client is in a while loop where it reads a line(StreamReader.ReadLine()) and then doing some operations with the line it reads. When the serever gets closed, i also close the tcp connection server-side. So, i'm expecting the client to see a SocketException caused by the readline, catch it and exit. But the exception doesn't get caught! Here's the client loop code:

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

When i close the server, visual studio tells me that a "System.Net.Sockets.SocketException" first-chance exception was raised in System.dll, but i cannot catch it. Why does that happen? i also tried to catch any generic exception with a

catch
{
}

block, but that doesn't work either.

Any help will be appreciated!

EDIT: after trying some more times, i actually found out that SocketException doesn't get raised at all. That's so weird, as i said in a comment, in the opposite situation, when the client gets closed before the server, the exception gets raised and i can canth it. I don't really know what's going on....

like image 953
l.moretto Avatar asked Jul 12 '11 14:07

l.moretto


1 Answers

If I understand you well the scenario is when you call Stop method at TcpListener object "_server.Stop()", it will not throw SocketException at the client side when call Read on the stream... I don't know why this is happening but I have a work ground around it. it is by accessing to the underlying Socket on the TcpListener and call Shutdown on it:

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

Edit: You stated at comment:

actually i'm closing the tcpclient returned by the listener on the accept method. connClient.Close()

If are stopping the tcpListerner "_server.Stop()" and then close the clients getted from _server.AcceptTcpCleint() method, then at the at reader.ReadLine() will throw IOException: Unable to read data from the transport connection: A blocking operation was interrupted by a call to WSACancelBlockingCall I tested it myself.

like image 174
Jalal Said Avatar answered Sep 19 '22 11:09

Jalal Said