views:

144

answers:

2

I have created a simple tcp based "echo protocol" and notice that I suffer from handle leak on the server when the client forcibly closes the connection (sends a reset).

I catch the ConnectionReset and dispose the socket in the same way I do when the socket is closed (socket.Shutdown and socket.close). As anybody encountered such a problem? The ConnectionReset exception is thrown while I'm doing a socket.Read, if it matters.

Thanks.

Edit: Microsoft's DebugDiag tool suggests those are event handlers created by MSCORLIB. Needless to say that I don't create those directly (but they are created somewhere by the .net library)

A: 

Socket.Recieve and Socket.Write are, unfortunately, the only places to detect when the other end closes it's sockets forcibly rather than correctly.

Socket.Close() should (according to my intellisense) release the socket handle.

So first make sure Socket.Close() is indeed being called. Then check other places for handle leaks, are you using any objects that require disposing that aren't being disposed? Such as opening FileStreams?

Sekhat
It is indeed being called. No file streams, but anyway, I do treat reset sockets as nicely closed sockets. (and I do get the exception while performing Read)
r0u1i
A: 

I think you do it right:

Socket.Close should free all managed and unmanaged ressources associated to the socket.

But did you also try to set

socket = null;

And maybe (after that) use

GC.Collect();

to manually trigger the garbage collector, is the leak still present after this?

Another idea: How do you monitor the handle leak? The OS might keep a closed TCP connection in memory for a long time (minutes), this is normal behaviour.

Tarnschaf
Yes, I'm doing all of those and the leak is still present. I see the handle leak in task manager, but running net stat shows that there are no close-waiting connections.Microsoft's DebugDiag tool suggests those handles are event-handles, that's the only clue I've got.
r0u1i
okay, is the leak also present after destroying the accepting TcpListener object?
Tarnschaf
no, it isn't (I first thought it does, but I was mistaken). What does that tell us? After all, I can't stop the listener from time to time
r0u1i
i guess it only tells us that the handles are still associated and not "lost". maybe you have to provide more code. are threads or objects involved that could still have a reference to the socket?
Tarnschaf