我有下面的HTTP listener方法,这很大程度上受到了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();
}发布于 2014-10-02 17:54:01
您似乎已经删除了MSDN HttpListener Class页面上提到的注释:
// URI前缀必填,例如"http://contoso.com:8080/index/“。
所以就这么叫吧:
public static void Main(string[] args)
{
HttpListener(new[] { "http://localhost/" });
}但请注意,此示例将仅处理一个请求,然后退出。如果您的后续问题是“如何让它处理多个请求?”,请参阅Handling multiple requests with C# HttpListener。
发布于 2017-10-22 22:06:38
你可以这样做:
public void ListenTraces()
{
httpListener.Prefixes.Add(PORT_HOST);
try
{
httpListener.Start();
}
catch (HttpListenerException hlex)
{
log.Warn("Can't start the agent to listen transaction" + hlex);
return;
}
log.Info("Now ready to receive traces...");
while (true)
{
var context = httpListener.GetContext(); // get te context
log.Info("New trace connexion incoming");
Console.WriteLine(context.SomethingYouWant);
}
}https://stackoverflow.com/questions/26157475
复制相似问题