Noor Mohammed
Noor Mohammed

Reputation: 1

How to fix httplistener after an exception happens

I have this HttpListener that receives multiple requests , the problem is that every time an exception happens the listener stops working I tried stoping and restarting the server but it still gets stuck in GetContextAsync. I am new to asynchronous programming.

public class HttpServer{

 public HttpServer(string id)
    {
        try {
            _id= id;
            var prefix = $"http://localhost:39633/queries/{id}/";
            _listener = new HttpListener();
           _listener.Start();

        }
        catch (Exception e) {

        }
    }

    public async Task Start()
    {
        try {
            while(true ) {
                var context = await _listener.GetContextAsync().ConfigureAwait(false);// it stays here
                HandleRequest(context); // handle incoming requests
            }
        }
        catch (Exception e) {

        }
    }
}

I want the server to keep running , is there a way to do that

Upvotes: 0

Views: 1665

Answers (1)

Gabriel Luci
Gabriel Luci

Reputation: 40998

Your catch block is outside your loop. So every time an exception happens, it leaves the loop. So you just need to invert your while and try so you can examine the Exception (while still inside the loop) and decide if you want to try again or abort.

public async Task Start() {
    while(true) {
        try {
            var context = await _listener.GetContextAsync().ConfigureAwait(false);// it stays here
            HandleRequest(context); // handle incoming requests
        } catch (HttpListenerException e) {
            // examine e.ErrorCode to see what the problem was and
            // decide to continue or return
        } catch (Exception e) {
            // decide to continue or return
        }
    }
}

The documentation for HttpListener.GetContext (which works the same as GetContextAsync) says that when it throws an HttpListenerException, that means that:

A Win32 function call failed. Check the exception's ErrorCode property to determine the cause of the exception.

In my experience, that is only thrown when you stop the listener intentionally. But maybe something else went wrong. If you tell us the message in the exception, we might be able to help more.

If it helps you, I did write an article with sample code about creating a basic HttpListener web service.

Upvotes: 1

Related Questions