zoukankan      html  css  js  c++  java
  • 一个简单的HttpListener服务结构

    前文中我简单的介绍了一下HttpListener的用法,并给出了一个简单的代码示例,那个例子主要是为了演示功能,力求简单,而实际使用中并不方便:服务器每启动一次只能处理一个请求。

    我针对这个问题简单的将该结构改进了一下,代码如下:

    using System;
    using System.Collections.Generic;
    using System.Text;

    using System.Net;

    namespace ConsoleApplication1
    {
        
    class Program
        
    {
            
    static void Main(string[] args)
            
    {
                HttpListener listener 
    = new HttpListener();
                listener.Prefixes.Add(
    "http://localhost/"); //要监听的url范围
                listener.Start();   //开始监听端口,接收客户端请求
                Console.WriteLine("Listening");

                
    try
                
    {
                    
    while (true)
                    
    {
                        
    //获取一个客户端请求为止
                        HttpListenerContext context = listener.GetContext();
                        
    //将其处理过程放入线程池
                        System.Threading.ThreadPool.QueueUserWorkItem(ProcessHttpClient, context);
                    }

                }

                
    catch (Exception e)
                
    {

                    Console.WriteLine(e.Message);
                }

                
    finally
                
    {
                    listener.Stop();    
    //关闭HttpListener
                }

                
            }

            
    //客户请求处理
            static void ProcessHttpClient(object obj)
            
    {
                HttpListenerContext context 
    = obj as HttpListenerContext;
                HttpListenerRequest request 
    = context.Request;
                HttpListenerResponse response 
    = context.Response;

                
    //do something as you want
                string responseString = string.Format("<HTML><BODY> {0}</BODY></HTML>", DateTime.Now);
                
    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
                response.ContentLength64 
    = buffer.Length;
                System.IO.Stream output 
    = response.OutputStream;
                output.Write(buffer, 
    0, buffer.Length);
                
                
    //关闭输出流,释放相应资源
                output.Close();
            }

        }

    }


    在新的代码中,服务器循环阻塞接收每个客户端的请求,然后将处理过程放如线程池,在新的线程中处理,服务器可以接着接收下一个请求并处理了。

    我的目的是为了学习Http服务而推出的一个测试架构,并不需要很完善的框架和很高的效率,采用的线程池形式处理简单,直观且有效。并且将客户处理单独放在ProcessHttpClient函数中执行,如果要学习其它功能,只需要修改该函数即可。

  • 相关阅读:
    使用MaxCompute Java SDK 执行任务卡住了,怎么办?
    通过编辑文件的方式对DNS服务器进行配置
    2009级计算机应用 嵌入式方向课表
    微软首宗针对中国大企业盗版案宣判:获赔217万
    小數點的運算[討論區- PHP新手區] : 台灣PHP聯盟
    Linux C编程一站式学习
    用wget做站点镜像
    2008级嵌入式方向学生 学习成果(创意)
    Linux领航未来操作系统
    fedora12 微软雅黑
  • 原文地址:https://www.cnblogs.com/TianFang/p/610668.html
Copyright © 2011-2022 走看看