gpt4 book ai didi

C# 和在后台运行 HttpListener

转载 作者:行者123 更新时间:2023-12-03 12:47:04 26 4
gpt4 key购买 nike

我创建了简单的 HttpListener 来监听端口 9090 并根据请求的 URL 将一些信息写入控制台。

但我卡住了 :( 我想到了多线程、基于事件的系统,但我没有设法用它做任何事情。

这是我作为单独的控制台应用程序启动的监听器的代码:

string urlTemplate = String.Format("/prefix/{0}/suffix", id);
string prefix = String.Format("http://localhost:9090/");

HttpListener listener = new HttpListener();
listener.Prefixes.Add(prefix);

listener.Start();

Console.WriteLine("Listening to {0}...", prefix);

while (true)
{
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;

//Response object
HttpListenerResponse response = context.Response;

//Construct response
if (request.RawUrl.Contains(urlTemplate) && request.HttpMethod == "POST")
{
string requestBody;
Stream iStream = request.InputStream;
Encoding encoding = request.ContentEncoding;
StreamReader reader = new StreamReader(iStream, encoding);
requestBody = reader.ReadToEnd();

Console.WriteLine("POST request on {0} with body = [{1}]", request.RawUrl, requestBody);

response.StatusCode = (int)HttpStatusCode.OK;

//Return a response
using (Stream stream = response.OutputStream) { }
}
else
{
response.StatusCode = (int)HttpStatusCode.BadRequest;
Console.WriteLine("Invalid HTTP request: [{0}] {1}", request.HttpMethod, request.Url);
using (Stream stream = response.OutputStream) { }
}
}

我决定将它用作单元测试的实用程序(也许在其他地方)。因此,当测试开始时,我需要配置监听器,运行它,然后发出一些请求并接收信息(监听器之前写入控制台),并在测试结束时停止监听器。

我的主要想法是将此监听器封装到单独的类 MyHttpListener 中,该类具有方法:StartListener()StopListener()

但是当我调用 StartListener() 时,我的测试由于无限 while 循环而卡住。我试图创建单独的后台线程或基于事件的系统,但我缺乏使用它们的经验,阻止了我这样做。我已经花了很多时间试图找到解决方案,但一无所获。

希望你能帮我找到解决这种琐碎任务的方法。

提前致谢。

最佳答案

其中一个响应者的变体(似乎他删除了他的帖子)看起来不错,但对我不起作用。我试图修复问题以便它开始工作,但最后那个变体让我知道了如何解决问题 - 使用多线程和事件 :)

这是我现在拥有的并且它有效:

public delegate void HttpListenerRequestHandler(object sender, HttpListenerEventArgs e);
public event HttpListenerRequestHandler OnCorrectRequest;

...

if(OnCorrectRequest != null)
OnCorrectRequest(this, new HttpListenerEventArgs(response));
lock (threadLock)
{
Console.WriteLine("POST request on {0} with body = [{1}]", request.RawUrl, requestBody);
}

...

public class HttpListenerEventArgs : EventArgs
{
public readonly HttpListenerResponse response;
public HttpListenerEventArgs(HttpListenerResponse httpResponse)
{
response = httpResponse;
}
}

为了在主线程中接收来自 HttpListener 的详细响应,我使用以下内容:

private HttpListenerResponse response;

public void HttpCallbackRequestCorrect(object sender, HttpListenerEventArgs e)
{
response = e.response;
Console.WriteLine("{0} sent: {1}", sender, e.response.StatusCode);
}

不幸的是,我有以下异常,我不知道如何处理:

System.Net.HttpListenerException: The I/O operation has been aborted because of either a thread exit or an application request at System.Net.HttpListener.GetContext()

关于C# 和在后台运行 HttpListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9415763/

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