【发布时间】:2014-11-27 05:52:10
【问题描述】:
我有以下 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();
}
【问题讨论】:
-
请说明您想从这里去哪里。
-
我的目标是能够运行此侦听器,然后使用网络浏览器发出 HTTP 请求,如“localhost”,或者如果它是我网络上的另一台机器,那么我的机器的 IP 地址.然后它应该以一个简单的 HTML 页面进行响应。
-
您可以从您的
Main()方法调用HttpListener(new string[] { "http://*:80/" });,以指定您要处理端口80(默认http 端口)上的流量。