简体   繁体   English

带有HTTPListener的Win7服务在一个请求后停止响应

[英]Win7 service with HTTPListener stops responding after one request

I'm a novice c# developer - trying to write a simple win7 service. 我是一位C#新手开发人员-试图编写一个简单的win7服务。

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. 该服务应启动HTTPListener并侦听传入的浏览器请求,当收到请求时,它将返回响应并继续侦听其他请求。 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. 我可能需要在某个地方循环,但我对API并不熟悉,所以我做的事情也可能错了。

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); 
}  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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