我有以下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();
}
最佳答案
您似乎删除了MSDN HttpListener Class页面上提到的评论:
所以就这样称呼它:
public static void Main(string[] args)
{
HttpListener(new[] { "http://localhost/" });
}
但是请注意,此示例将仅处理一个请求,然后退出。如果您的后续问题是“我如何使其能够处理多个请求?”,请参见Handling multiple requests with C# HttpListener。
关于c# - HttpListener的使用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26157475/