ITPub博客

首页 > 应用开发 > > 基于.NET开发异步HTTP WEB Server

基于.NET开发异步HTTP WEB Server

作者:muren 时间:2019-09-16 14:11:13 0 删除 编辑

请问园子中的各位大佬们,如果使用HttpListener如何开发一款支持异步的web服务器,如果大佬们有github上的现成的例子的话,恳请甩上一下,供小弟拜读一番,自己也做了一下,如果大佬们有时间的话还请斧正.

这款异步web服务器主要用来对接CoolQ HTTP API,接收上报的请求并托管到自己的程序进行处理,下面粘贴一下小弟的拙作,还请斧正https://github.com/f472918106/FlyingCube/blob/master/FlyingCube/Service/AsyncHttpService.cs

/// <summary>
        /// 开始监听,将消息加入消息队列
        /// </summary>
        /// <returns></returns>
        public async Task Start()
        {
            listener.Start();
            current.richTextBox_MsgQueue.Text += "[" + DateTime.Now + "] 开始监听"+ServiceUrl+"\n";
            while (true)
            {
                current.richTextBox_MsgQueue.Text += "[" + DateTime.Now + "] 监听中... \n";
                var context = await listener.GetContextAsync();
                current.richTextBox_MsgQueue.Text += "[" + DateTime.Now + "] 接收到一条新的请求... \n";
                await ReportContext(context);
                await ReturnResponse(context);
            }
        }

        /// <summary>
        /// 停止监听
        /// </summary>
        /// <returns></returns>
        public async Task Stop()
        {
            listener.Stop();
            await Task.Delay(TimeSpan.FromSeconds(2));
        }

        /// <summary>
        /// 异步上报HttpListentContext实体
        /// </summary>
        /// <param name="context">HttpListentContext实体</param>
        /// <returns></returns>
        private async Task ReportContext(HttpListenerContext context)
        {
            StreamReader reader = new StreamReader(context.Request.InputStream);
            current.richTextBox_MsgQueue.Text += "[" + DateTime.Now + "] 正在读取请求... \n";
            string request = await reader.ReadToEndAsync();
            current.richTextBox_MsgQueue.Text += "[" + DateTime.Now + "] 请求读取完成,内容如下: \n"+request+"\n";
            reader.Close();
            MsgQueue.Enqueue(request);
            current.richTextBox_MsgQueue.Text += "[" + DateTime.Now + "] 已加入消息队列. \n";
            await AsyncTaskService.TaskEnqueue(request);
        }

目前使用的是HttpListener.GetContextAsync()方法,之前也尝试过用HttpListener.BeginGetContext通过回调函数递归调用当前函数,来实现循环监听,但是由于眼拙,没有看出明显的异步操作特点,就改用了HttpListener.GetContextAsync(),现在实现的效果就是同一秒可以接收多条请求并创建相应作业加入作业队列,但是感觉还是有些怪怪的,小弟愚笨,还请各位大佬提点提点,除此之外还有一个小问题,就是async和await,当出现await以后具体程序是怎么执行的,emmmmm,看了很多大佬的帖子,自己也单步运行测试了很多次还是没有确定await出现以后究竟发生了什么,在此小弟先行谢过各位大佬!!!

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2388/viewspace-3157999/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-15

  • 博文量
    104
  • 访问量
    822