How to avoid a TCP Socket from throwing a SocketException on disconnect?
I'm working on some C# server project, and it's going quite good.
Today I changed from Async reading, to normal reading, using polling. Now when I was reading async this wasn't a problem, but now it is.
When the client disconnects, the socket throws a SocketException, and that exception causes some pretty long delay. If I don't stop it from throwing that exception, the entire server will freeze for about half a second. And that might not seem worth the trouble, but the server will get a pretty high amount of connects and disconnects, so it really takes too long.
Now I'm already checking the Socket.Connected property, that returns true, but after the read method it returns false.
So does anyone know how to 'update' the status of the connection,开发者_如何学JAVA before trying to read it?
PS: I am catching the exception, it's just that the delay is too big.
In typical TCP development, having a connection closed unexpectedly should be an exceptional case. You should consider implementing a more graceful system, where the one side first sends a message indicating that it's going to disconnect, that way both sides can then close the connection without any failures.
Bear in mind that activity is required to determine if a connection is closed or not. Per the MSDN docs on Socket.Connected, that property only reflects whether or not the connection was connected at the time the last operation was attempted.
If you're doing anything non-trivial with this, you should be isolating your connections with threads (not necessarily one thread per connection, as anything with high traffic would quickly overwhelm the system), but it should not be possible for a single connection to monopolize the entire server, whether that's from a lengthy operation that the connection initiates or a timeout expiration.
Looks like the Socket is reading from the closed stream to some kind of timeout maybe?
I would just use a second thread, or see if I could change the timeout to 0 after the disconnect?
精彩评论