gpt4 book ai didi

c# - HttpListener 的使用

转载 作者:太空狗 更新时间:2023-10-30 00:31:26 25 4
gpt4 key购买 nike

我有以下 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 中提到的评论页:

// URI prefixes are required, for example "http://contoso.com:8080/index/".

所以就这样调用它:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com