如何允许我的AsyncCallback侦听器多次运行?

时间:2014-07-23 19:23:06

标签: c# httplistener

我有这个:

 HttpListener listener = new HttpListener();
        listener.Prefixes.Add("http://+:8080/");
        listener.Start();

        IAsyncResult asyncResult = listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener);



public static void ListenerCallback(IAsyncResult result)
    {
        Console.WriteLine("hit");
        HttpListener listener = (HttpListener)result.AsyncState;
        // Call EndGetContext to complete the asynchronous operation.
        HttpListenerContext context = listener.EndGetContext(result);
        HttpListenerRequest request = context.Request;
        StreamReader reader = new StreamReader(request.InputStream);
        Console.WriteLine(reader.ReadToEnd());
        //Obtain a response object.
        HttpListenerResponse response = context.Response;
        // Construct a response. 
        string responseString =  "Hello world!";
        byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
        // Get a response stream and write the response to it.
        response.ContentLength64 = buffer.Length;
        System.IO.Stream output = response.OutputStream;
        output.Write(buffer, 0, buffer.Length);
        output.Close();
        reader.Close();
    }

它有效。一旦。如果您再次发送相同的请求,您将得不到任何回复,服务器将无法识别任何请求。

我做错了什么,或者我需要做些什么才能让听众不止一次听?

1 个答案:

答案 0 :(得分:1)

Jus再次调用BeginGetContext。有两种方法可以做到这一点是一个循环,您可以在其中并行接受请求但是您需要以某种方式控制并发调用的数量,另一种方法是在回调代码的末尾调用该方法。或者,您可以在循环中使用同步方法。