C# HttpListener处理多个请求

C# HttpListener处理多个请求,c#,http,C#,Http,我有一个HttpListener,它非常适合一个requesst,但是在完成请求后它就会关闭。我感兴趣的是一个侦听器,它保持与客户机的连接,直到指定URL中没有更多文件为止。我尝试过摆弄线程和异步调用,但到目前为止,我还没能让它工作起来。我很难想象有什么相对简单的方法可以让HttpListener保持连接,而不是在完成每个请求后关闭 public static void Listener(string[] prefixes) { if (!HttpListener.IsS

我有一个HttpListener,它非常适合一个requesst,但是在完成请求后它就会关闭。我感兴趣的是一个侦听器,它保持与客户机的连接,直到指定URL中没有更多文件为止。我尝试过摆弄线程和异步调用,但到目前为止,我还没能让它工作起来。我很难想象有什么相对简单的方法可以让HttpListener保持连接,而不是在完成每个请求后关闭

public static void Listener(string[] prefixes)
    {
        if (!HttpListener.IsSupported)
        {
            Console.WriteLine("Windows XP SP2 or Server 2003 is required to use the HttpListener class.");
            return;
        }
        // URI prefixes are required, 
        // for example "http://contoso.com:8080/index/".
        if (prefixes == null || prefixes.Length == 0)
            throw new ArgumentException("prefixes");


        // Create a listener.
        HttpListener listener = new HttpListener();
        // Add the prefixes. 
        foreach (string s in prefixes)
        {
            listener.Prefixes.Add("http://" + s + "/");
        }


        listener.Start();
        Console.WriteLine("\nListening...");

        HttpListenerContext context = listener.GetContext();
        Console.WriteLine("Request received...\n");

        HttpListenerRequest request = context.Request;

        // Obtain a response object.
        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;


        #region Load image and respond

        // Load the image
        Bitmap bm = new Bitmap("C:\\MyFolder\\image_1\\");
        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;
        System.IO.Stream output = response.OutputStream;
        output.Write(buffer, 0, buffer.Length);

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

        #endregion
以下是节目:

    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.Listener(ips);

        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }

        //Manually setting the IP - not optimal!
        //string[] ipstring = new string[1] { "10.10.180.11:8080" };
        //Response.Listener(ipstring);


    }

}
类程序
{
静态void Main(字符串[]参数)
{
字符串名称=(args.Length<1)?Dns.GetHostName():args[0];
尝试
{//查找IPv4地址
IPAddress[]addrs=Array.FindAll(Dns.GetHostEntry(string.Empty).AddressList,
a=>a.AddressFamily==AddressFamily.InterNetwork);
Console.WriteLine(“您的IP地址是:”);
foreach(地址中的IP地址地址)
Console.WriteLine(“{0}{1}”,名称,地址);
//自动设置IP地址
字符串[]ips=addrs.Select(ip=>ip.ToString()).ToArray();
响应侦听器(ips);
}
捕获(例外e)
{
控制台写入线(e.Message);
}
//手动设置IP-非最佳!
//string[]ipstring=新字符串[1]{“10.10.180.11:8080”};
//Response.Listener(ipstring);
}
}

是-您正在调用
GetContext
一次,为该请求提供服务,然后停止

相反,您应该在循环中调用
GetContext
。根据您是否希望能够同时处理多个请求,您可能在一个线程中有
GetContext
,然后将每个请求交给一个单独的(可能是线程池)线程来响应它


稍微棘手的一点是关闭-如果你想要一个干净的关机,你需要找出何时停止循环(以及如果你在一个<代码> GeValue调用中间),等待未完成的请求完成。< /P> < P>在处理一个请求后停止听,因为你只是停止了听。您需要实现一些类似于等待循环的东西

可以在上找到对您有帮助的示例

请注意代码的这一部分及其在示例中的使用方式:

private void startlistener(object s)
{
    while (true)
    {               
        ////blocks until a client has connected to the server
        ProcessRequest();
    }
}
“我有一个HttpListener,它非常适合一个requesst,但是在完成请求后它会关闭”-。