首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用HttpListener同时处理多个连接?

如何使用HttpListener同时处理多个连接?
EN

Stack Overflow用户
提问于 2015-02-02 16:04:38
回答 2查看 11.8K关注 0票数 10

在我构建的应用程序中,需要能够同时为多个客户端提供服务的for服务器。

为此,我使用HttpListener对象。使用它的Async方法\events BeginGetContextEndGetContext

在委托的方法中,会调用侦听器重新开始侦听,并且它可以工作。多半是。

提供的代码混合了我在这里和那里找到的代码,以及一个延迟,以模拟数据处理瓶颈。

问题是,只有在最后一个连接被服务之后,它才开始管理下一个连接。对我来说没用。

代码语言:javascript
复制
public class HtServer {


    public void startServer(){
        HttpListener HL = new HttpListener();
        HL.Prefixes.Add("http://127.0.0.1:800/");
        HL.Start();
        IAsyncResult HLC = HL.BeginGetContext(new AsyncCallback(clientConnection),HL);   
    }

    public void clientConnection(IAsyncResult res){
        HttpListener listener = (HttpListener)res.AsyncState;
        HttpListenerContext context = listener.EndGetContext(res);
        HttpListenerRequest request = context.Request;
        // Obtain a response object.
        HttpListenerResponse response = context.Response;
        // Construct a response. 
        // add a delay to simulate data process
        String before_wait = String.Format("{0}", DateTime.Now);
        Thread.Sleep(4000);
        String after_wait = String.Format("{0}", DateTime.Now);
        string responseString = "<HTML><BODY> BW: " + before_wait + "<br />AW:" + after_wait + "</BODY></HTML>";
        byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
        // Get a response stream and write the response to it.
        response.ContentLength64 = buffer.Length;
        System.IO.Stream output = response.OutputStream;
        // You must close the output stream.
        output.Write(buffer, 0, buffer.Length);
        output.Close();
        listener.BeginGetContext(new AsyncCallback(clientConnection), listener);
    }
}

编辑

代码语言:javascript
复制
    private static void OnContext(IAsyncResult ar)
    {
        var ctx = _listener.EndGetContext(ar);
        _listener.BeginGetContext(OnContext, null);

        Console.WriteLine(DateTime.UtcNow.ToString("HH:mm:ss.fff") + " Handling request");

        var buf = Encoding.ASCII.GetBytes("Hello world");
        ctx.Response.ContentType = "text/plain";

        // prevent thread from exiting.
        Thread.Sleep(3000);
        // moved these lines here.. to simulate process delay
        ctx.Response.OutputStream.Write(buf, 0, buf.Length);
        ctx.Response.OutputStream.Close();
        Console.WriteLine(DateTime.UtcNow.ToString("HH:mm:ss.fff") + " completed");
    }

输出为

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-02-02 16:13:12

井。这是因为在处理完第一个上下文之后,您开始获取下一个上下文。别干那事。直接获取下一个上下文:

代码语言:javascript
复制
public void clientConnection(IAsyncResult res){
    HttpListener listener = (HttpListener)res.AsyncState;
    HttpListenerContext context = listener.EndGetContext(res);

    //tell listener to get the next context directly.
    listener.BeginGetContext(clientConnection, listener);

    HttpListenerRequest request = context.Request;
    // Obtain a response object.
    HttpListenerResponse response = context.Response;
    // Construct a response. 
    // add a delay to simulate data process
    String before_wait = String.Format("{0}", DateTime.Now);
    Thread.Sleep(4000);
    String after_wait = String.Format("{0}", DateTime.Now);
    string responseString = "<HTML><BODY> BW: " + before_wait + "<br />AW:" + after_wait + "</BODY></HTML>";
    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
    // Get a response stream and write the response to it.
    response.ContentLength64 = buffer.Length;
    System.IO.Stream output = response.OutputStream;
    // You must close the output stream.
    output.Write(buffer, 0, buffer.Length);
    output.Close();
}

下面是我的示例代码,它证明了它是有效的(根据OP的请求进行更新):

代码语言:javascript
复制
class Program
{
    private static HttpListener _listener;

    static void Main(string[] args)
    {
        _listener = new HttpListener();
        _listener.Prefixes.Add("http://localhost/asynctest/");
        _listener.Start();
        _listener.BeginGetContext(OnContext, null);

        Console.ReadLine();
    }

    private static void OnContext(IAsyncResult ar)
    {
        var ctx = _listener.EndGetContext(ar);
        _listener.BeginGetContext(OnContext, null);

        Console.WriteLine(DateTime.UtcNow.ToString("HH:mm:ss.fff") + " Handling request");

        var buf = Encoding.ASCII.GetBytes("Hello world");
        ctx.Response.ContentType = "text/plain";

        // simulate work
        Thread.Sleep(10000);

        ctx.Response.OutputStream.Write(buf, 0, buf.Length);
        ctx.Response.OutputStream.Close();


        Console.WriteLine(DateTime.UtcNow.ToString("HH:mm:ss.fff") + " completed");
    }
}

生成:

这两个请求都开始被直接处理。

为什么上面的代码可以工作

HTTP有一种叫做流水线的东西。这意味着通过同一连接接收的所有请求都必须以相同的顺序得到响应。但是,内置的HttpListener似乎不支持流水线,而是在处理第二个请求之前完成对第一个请求的响应。因此,确保每个请求都通过新的连接发送是很重要的。

要做到这一点,最简单的方法是在尝试代码时使用不同的浏览器。我这样做了,正如您所看到的,我的两个请求都是同时处理的。

票数 20
EN

Stack Overflow用户

发布于 2015-02-02 16:28:48

试试这个吧..

这将使用异步编码来确保没有阻塞。阻塞意味着线程处于休眠状态,这通常是程序“冻结”的原因。通过使用此代码,您可以运行非阻塞,这意味着几乎不可能“冻结”应用程序。

代码语言:javascript
复制
public async Task handleClientConnection(HttpListener listener){
    HttpListenerContext context = await listener.GetContextAsync();
    var ret = handleClientConnection(listener);

    HttpListenerRequest request = context.Request;
    // Obtain a response object.
    HttpListenerResponse response = context.Response;
    // Construct a response. 
    // add a delay to simulate data process
    String before_wait = String.Format("{0}", DateTime.Now);
    await Task.Wait(4000);
    String after_wait = String.Format("{0}", DateTime.Now);
    string responseString = "<HTML><BODY> BW: " + before_wait + "<br />AW:" + after_wait + "</BODY></HTML>";
    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
    // Get a response stream and write the response to it.
    response.ContentLength64 = buffer.Length;
    using(System.IO.Stream output = response.OutputStream)
        output.Write(buffer, 0, buffer.Length);

    await ret;
}

public void startServer(){
    HttpListener HL = new HttpListener();
    HL.Prefixes.Add("http://127.0.0.1:800/");
    HL.Start();
    await handleClientConnection(HL);
}
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28273345

复制
相关文章

相似问题

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