使用HttpListener

Kha*_*775 4 c# http

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

 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();
    }
Run Code Online (Sandbox Code Playgroud)

Cod*_*ter 8

您似乎已删除MSDN HttpListener类页面上提到的注释:

// URI前缀是必需的,例如" http://contoso.com:8080/index/ ".

所以就这样称呼它:

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

但请注意,此示例仅处理一个请求,然后退出.如果您的后续问题是"如何让它处理多个请求?" ,请参阅使用C#HttpListener处理多个请求.