简体   繁体   中英

Win7 service with HTTPListener stops responding after one request

I'm a novice c# developer - trying to write a simple win7 service.

The service should start HTTPListener and listen for incoming browser requests, when a request is received it returns a response and continue to listen for additional requests. I don't need to deal with parallelism since there would be no more than one request at a time (and very short).

I used the following code, but after the first response the service stops responding. I may need a loop somewhere but I am not familiar with the API so I may also be wrong with what I'm doing.

Thank you for your help.

    protected override void OnStart(string[] args)
    {
        HttpListener listener = new HttpListener();
        listener.Prefixes.Add("http://localhost:9999/");
        listener.Start();

        listener.BeginGetContext(new AsyncCallback(OnRequestReceive), listener);
     }

    private void OnRequestReceive(IAsyncResult result)
    {
        HttpListener listener = (HttpListener)result.AsyncState;
        HttpListenerContext context = listener.EndGetContext(result);
        HttpListenerResponse response = context.Response;
        byte[] buff = {1,2,3};

        response.Close(buff, true);
    } 

You're almost there! After receiving one request, you need to start listening for another one.

private void OnRequestReceive(IAsyncResult result) 
{ 
    HttpListener listener = (HttpListener)result.AsyncState; 

    HttpListenerContext context = listener.EndGetContext(result); 
    HttpListenerResponse response = context.Response; 
    byte[] buff = {1,2,3}; 

    response.Close(buff, true); 

    // ---> start listening for another request
    listener.BeginGetContext(new AsyncCallback(OnRequestReceive), listener); 
}  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM