views:

71

answers:

2

In an application I'm developing, I have the need to handle a socket-timeout differently from a general socket exception. The problem is that many different issues result in a SocketException and I need to know what the cause was.

There is no inner exception reported, so the only information I have to work with is the message:

"A connection attempt failed because the connected party did not 
properly respond after a period of time, or established connection 
failed because connected host has failed to respond"

This question has a general and specific part:

  1. is it acceptable to write conditional logic based upon the textual representation of an exception?
  2. Is there a way to avoid needing exception handling?

Example code below...

try 
{
    IPEndPoint endPoint = null; 
    client.Client.ReceiveTimeout = 1000;
    bytes = client.Receive(ref endPoint);
}
catch( SocketException se )
{
    if ( se.Message.Contains("did not properly respond after a period of time") )
    {
        // Handle timeout differently..
    }
}

I'm wanting to cease the "wait for new data" every now and again, so that my worker thread can look to see whether it has been asked to gracefully close - I would rather avoid cross-thread termination of the socket to provide this mechanism.

+8  A: 

of course it is! there are more descriptive fields in SocketException, you should not perform string comparison. http://msdn.microsoft.com/library/system.net.sockets.socketexception_members.aspx, especially:

  • ErrorCode
  • NativeErrorCode
  • SocketErrorCode
Andrey
Why had I completely missed those? Thanks.
Ray Hayes
+2  A: 

Exceptions are Culture relevant, I have "German" exception messages. Use the SocketErrorCode.

chriszero