首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >HttpListener问题:每个HttpListener请求都会导致HttpListener返回的两个上下文

HttpListener问题:每个HttpListener请求都会导致HttpListener返回的两个上下文
EN

Stack Overflow用户
提问于 2011-10-15 23:10:39
回答 1查看 3K关注 0票数 4

我在一个windows服务应用程序中安装了一个小小的嵌入式HTTP服务器,用于监听来自网络上使用HTTP语言的其他设备的更新。

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

代码语言:javascript
运行
复制
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();
}

有什么明显的东西是我错过的,我已经没有想法去追踪这个问题了。

EN

回答 1

Stack Overflow用户

发布于 2011-10-16 19:24:57

好的,问题是我使用web浏览器来测试HTTP连接,默认情况下,web浏览器也会发送一个favicon.ico请求。所以实际上有两个请求。谢谢@Inuyasha建议我和Wireshark核对一下。

票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7781278

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档