我一直在一個小型嵌入式HTTP服務器放在一個Windows服務應用程序中,該應用程序偵聽來自網絡上說HTTP的其他設備的更新。HttpListener問題:每個HTTP請求都會導致HttpListener返回兩個上下文
對於每個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來加倍確保。 – Amy
您可能還想看看OpenRasta,它爲您完成所有這些工作;-) - 我們已經成功地使用它將HTTP偵聽器嵌入到各種應用程序中,作爲應用程序的核心和用於監視等 - https://github.com/openrasta/openrasta-stable/wiki –
@Inuyasha,這是問題,網絡瀏覽器也發送favicon.ico的請求。 –