我在一个windows服务应用程序中安装了一个小小的嵌入式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();
}
有什么明显的东西是我错过的,我已经没有想法去追踪这个问题了。
发布于 2011-10-16 19:24:57
好的,问题是我使用web浏览器来测试HTTP连接,默认情况下,web浏览器也会发送一个favicon.ico请求。所以实际上有两个请求。谢谢@Inuyasha建议我和Wireshark核对一下。
https://stackoverflow.com/questions/7781278
复制相似问题