Я собрал небольшой встроенный HTTP-сервер в приложении службы 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();
}
Есть ли что-то очевидное, что мне не хватает, у меня закончились идеи отследитьвопрос.