HttpListener BeginGetContext突然停止了吗?

时间:2014-10-27 12:59:37

标签: c# http

我有一个HttpListener,我希望在每次请求后都不要关闭,所以我使用BeginGetContext异步检索请求。它只是不能正常工作。

Main正常启动,查找并为StartListening()函数分配我的IP地址。但是,当我在StartListening()中到达listener.BeginGetContext(new AsyncCallback(OnRequest), listener);并且它跳转到Main中的Response.StartListening(ips);然后停止。我不知道为什么。任何提示?

这是我到目前为止所拥有的。

这是我开始收听请求的地方:

 public static void StartListening(string[] prefixes)
    {
        HttpListener listener = new HttpListener();

        if (prefixes == null || prefixes.Length == 0)
            throw new ArgumentException("prefixes");

        foreach (string s in prefixes)
        {
            listener.Prefixes.Add("http://" + s + "/");
        }
        listener.Start();
        Console.WriteLine("\nListening...");

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

这是我处理请求的地方:

public static void OnRequest(IAsyncResult result)
    {
        HttpListener listener = (HttpListener) result.AsyncState;
        HttpListenerContext context = listener.EndGetContext(result);


        string url = context.Request.RawUrl;

        string[] split = url.Split('/');

        int lastIndex = split.Length - 1;

        int x, y, z;

        x = Convert.ToInt32(split[lastIndex]);
        y = Convert.ToInt32(split[lastIndex - 1]);
        z = Convert.ToInt32(split[lastIndex - 2]);

        HttpListenerResponse response = context.Response;

        Regex imageRegex = new Regex(@"SomethingSomething");
        var matches = imageRegex.Match(url);

        if (matches.Success)
        {
            string path = @"C:\SomeDir";

            path = String.Format(path, matches.Groups[1].Captures[0],
                                       matches.Groups[2].Captures[0],
                                       matches.Groups[3].Captures[0]);

            // Load the image
            Bitmap bm = new Bitmap(path);
            MemoryStream bmStream = new MemoryStream();
            bm.Save(bmStream, ImageFormat.Png);
            byte[] buffer = bmStream.ToArray();

            // Get a response stream and write the response to it.
            response.ContentLength64 = bmStream.Length;
            response.ContentType = "image/png";
            response.KeepAlive = true;
            Stream output = response.OutputStream;
            output.Write(buffer, 0, buffer.Length);

            // You must close the output stream.
            output.Close();
            listener.Stop();
        }

        response.Close();
        listener.BeginGetContext(new AsyncCallback(OnRequest), listener);
    }

这是我的主要内容:

class Program
{
    static void Main(string[] args)
    {
        string name = (args.Length < 1) ? Dns.GetHostName() : args[0];
        try
        {   //Find the IPv4 address 
            IPAddress[] addrs = Array.FindAll(Dns.GetHostEntry(string.Empty).AddressList,
                a => a.AddressFamily == AddressFamily.InterNetwork);
            Console.WriteLine("Your IP address is: ");
            foreach (IPAddress addr in addrs)
                Console.WriteLine("{0} {1}", name, addr);

            //Automatically set the IP address
            string[] ips = addrs.Select(ip => ip.ToString()).ToArray();
            Response.StartListening(ips);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

BeginGetContext之后,它以异步方式提取请求,因此它不会阻塞调用线程(在本例中为主线程)。并且因为它没有阻止它,所以主线程结束,因此你的程序也结束了,因为它是主线程。

您可以使用ManualResetEvent(在System.Threading命名空间中)来解决此问题。这会阻止主线程。

class Program
{
    public static ManualResetEvent ServerManualResetEvent;
    static void Main(string[] args)
    {
        try
        {
            // your code to start the server

            ServerManualResetEvent = new ManualResetEvent(false);
            ServerManualResetEvent.WaitOne();
        }
        catch
        {
            // your catch code
        }
    }
}

现在主线程被阻止,你的程序只有在你关闭它时停止,或者你从代码中停止它:

Program.ServerManualResetEvent.Set();

然后它不再阻止主线程。