This project is read-only.

How to stop HttpServer 1.1

Apr 28, 2011 at 6:44 AM

I need to stop and start a HttpServer based on some input from another module. My problem is HttpServer tries to clean up when you call stop but leaves sockets open that were previously created and handled via the call to CreateContext in the HttpListenerBase class.

From what I can tell these contexts dangle because the HttpClientContext objects have an incorrect if statement on line 343

if (Stream != null && Stream.CanRead)
	Stream.BeginRead(_buffer, _bytesLeft, _buffer.Length - _bytesLeft, OnReceive, null);
	_log.Write(this, LogPrio.Warning, "Could not read any more from the socket.");

I believe the issue is the Stream.CanRead property will always be true since the stream has been configured readable so the context will always try to asynchronously read more from the stream. This async callback means the object isn't cleaned up and the socket stays open until a socket time out occurs, but since my server is polled this doesn't seem to happen. I'm not entirely sure if this is the intended behaviour and the contexts are meant to be cleaned up in another way. From what I have seen no references are maintained to these created objects so I think this is the bug since I can't see another way to clean them up. I believe what should be checked is the DataAvailable property of the NetworkStream

if (Stream != null && Stream.CanRead && ((NetworkStream)Stream).DataAvailable)
This is how I quickly hacked it to confirm my suspicion and now the server appears to be operating correctly and the sockets are closed when the context has finished but again I'm not sure if this is by design so I was hoping someone could confirm my thoughts or instruct me of the correct way the stop the server.