exceptionlogoutmsn

How to handle socket error during logout routine


I am writing an instant messaging library. Currently, when a SocketException is raised while reading or writing to the socket, I start the logout routine from inside the application, passing the SocketException to the enduser as an argument of the LogoutEventArgs. This gives the end user a way of seeing what underlying exception actually caused the unrequested logout.

My question, is what am I to do, if during a user call to the Logout function, the socket actually throws an Exception.

Example - End user calls Logout function, and while the logout function is waiting for existing requests to end gracefully, the socket throws an exception in the reading thread.

I have two options as I see it -

  1. Pretend the error didn't occur, and just act like the socket disconnected as part of our Logout.

  2. When the socket exception is raised, see if a logout request is taking place, and if so, override it. Resulting in the original Logout request throwing an AlreadyLoggedOutException, as well as a separate logout event which passes the exception in the LogoutEventArgs.

Also, slightly related - What am I to do if the server initiates a shutdown that wasn't requested (ie.. the read call returns null).. the .NET Messenger server has a tendency to do this if you send a request it doesn't like. Do I treat this as an exception in itself?

I have found the whole disconnecting/logging out part of my library to be a major thorn in my side. I just can't seem to wrap my head around it. Does anyone know of any open source code applications that handle this situation beautifully?

I have been trying to tackle this thing in my head for so long, it's driving me mad.


Solution

  • I decided not to pass the SocketException to the end user, as a disconnect is not truly an exception and should be expected and dealt with. Instead there is a LogoutReason property on the LogoutEventArgs which specifies why the logout occured.

    I decided that if the disconnect occurs during Logout then that's not actually an exception for, as the logout was going to disconnect anyway. I simply disregard the exception in this case.