本文介绍了使用HttpListener的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下HTTP侦听器方法,受到MSDN使用HttpListener类的示例的启发。我对编程很新,我不知道从哪里开始从我的Main()初始化它。有什么建议吗?

I have the following HTTP listener method, greatly inspired by MSDN's example use of the HttpListener class. I'm fairly new to programming and I'm not sure where to go from here to initialize it from my Main(). Any suggestions?

 public static void HttpListener(string[] prefixes)
    {
        if (prefixes == null || prefixes.Length == 0)
            throw new ArgumentException("Prefixes needed");

        HttpListener listener = new HttpListener();

        foreach (string s in prefixes)
        {
            listener.Prefixes.Add(s);
        }
        listener.Start();
        Console.WriteLine("Listening..");

        HttpListenerContext context = listener.GetContext();
        HttpListenerRequest request = context.Request;
        HttpListenerResponse response = context.Response;

        string responseString = "<HTML><BODY> Test </BODY></HTML>";
        byte[] buffer = Encoding.UTF8.GetBytes(responseString);

        response.ContentLength64 = buffer.Length;
        Stream output = response.OutputStream;
        output.Write(buffer, 0, buffer.Length);

        output.Close();
        listener.Stop();
    }


推荐答案

你好像已经删除了页面:

You seem to have removed the comments that are mentioned on the MSDN HttpListener Class page:

所以就这样称呼:

public static void Main(string[] args)
{
    HttpListener(new[] { "http://localhost/" });
}

但请注意,此示例仅处理一个请求,然后退出。如果你的后续问题是如何让它处理多个请求?,请参阅。

But please note this example will handle only one request and then exit. If your follow-up question is then "How can I make it handle multiple requests?", see Handling multiple requests with C# HttpListener.

这篇关于使用HttpListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-23 01:59