tags:

views:

62

answers:

4

Let's say I've programmed an application which connects to a server using the Socket Class (TCP). If I encounter a SocketException while reading or writing, then obviously I have to do go ahead and run a disconnection routine to change the application's state to Disconnected.

But what if I've started to Disconnect, and while I'm cleaning up, a SocketException occurs?

The SocketException doesn't really mean anything to me, as I was going to shutdown the socket myself anyway.. so is it ok to swallow it?

I really want to know what the best practice for this situation is.

A: 

I disregard socket exceptions all the time, both with .net sockets and WCF.

Half the time I send call asynchronously, so if there is a disconnect, I don't find out about it until the timeout is hit, at which time I get a timeout exception that I ignore.

SLC
A: 

If something goes wrong while disconnecting, then in what state will the socket be? In the worst case, the remote socket will timeout. There really isn't anything you can do to fix that situation.

But as Joe R said, log the message - those exceptions might also occur because Disconnect() is being called twice, which is something you do want to know about. (Edit: don't know if that would cause an exception, but I hope you know what I mean :P)

deltreme
+2  A: 

There are situations where an exception is the 'normal' case. If I remember right, in some protocols (SMTP) clients will (can) disconnect when they are ready without sending a proper Close command. On the server side, you then always get an exception that is known to be harmless.

But make sure you only discard the specific exception type at the specific location.

Henk Holterman
+1  A: 

You still need to swallow some, especially when you design a retry mechanism. Right? If you don't swallow the first failure, how can you initialize a second attempt?

Lex Li