gpt4 book ai didi

c# - HttpListener 问题 : Each HTTP request results in two contexts returned by HttpListener

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

我一直在 Windows 服务应用程序中放置一个小型嵌入式 HTTP 服务器,用于监听来自网络上使用 HTTP 的其他设备的更新。

对于每个 HTTP 请求,处理请求/响应的代码会执行两次,我希望它只运行一次。我尝试使用 AsyncGetContext 方法并使用同步版本 GetContext 的代码 -最终结果是一样的。

代码

public void RunService()
{
var prefix = "http://*:4333/";
HttpListener listener = new HttpListener();
listener.Prefixes.Add(prefix);
try
{
listener.Start();
_logger.Debug(String.Format("Listening on http.sys prefix: {0}", prefix));
}
catch (HttpListenerException hlex)
{
_logger.Error(String.Format("HttpListener failed to start listening. Error Code: {0}", hlex.ErrorCode));
return;
}
while (listener.IsListening)
{
var context = listener.GetContext(); // This line returns a second time through the while loop for each request
ProcessRequest(context);
}
listener.Close();
}

private void ProcessRequest(HttpListenerContext context)
{
// Get the data from the HTTP stream
var body = new StreamReader(context.Request.InputStream).ReadToEnd();
_logger.Debug(body);

byte[] b = Encoding.UTF8.GetBytes("OK");
context.Response.StatusCode = 200;
context.Response.KeepAlive = false;
context.Response.ContentLength64 = b.Length;

var output = context.Response.OutputStream;
output.Write(b, 0, b.Length);
output.Close();
context.Response.Close();
}

有什么明显的我遗漏的吗,我已经没有办法追查这个问题了。

最佳答案

好的,问题是我使用网络浏览器测试 HTTP 连接,默认情况下网络浏览器也会发送对 favicon.ico 的请求。所以实际上遇到了两个请求。感谢@Inuyasha 建议我使用 Wireshark 进行检查。

关于c# - HttpListener 问题 : Each HTTP request results in two contexts returned by HttpListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7781278/

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