【发布时间】:2011-10-15 23:10:39
【问题描述】:
我已经在一个 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();
}
有什么明显的我遗漏的吗,我已经没有办法追查这个问题了。
【问题讨论】:
-
您绝对确定只有一个请求吗?通过在运行测试时观看 Wireshark 来加倍确定。
-
您可能还想看看 OpenRasta,它会为您完成所有这些 ;-) - 我们已经成功地使用它在各种应用程序中嵌入 HTTP 侦听器作为应用程序的核心并作为监控等的螺栓 - github.com/openrasta/openrasta-stable/wiki
-
@Inuyasha,这就是问题所在,网络浏览器也发送了对 favicon.ico 的请求。
标签: c# http asynchronous httplistener