技术头条 - 一个快速在微博传播文章的方式     搜索本站
您现在的位置首页 --> 系统架构 --> 通过HttpListener实现轻量级Web服务器[原创]

通过HttpListener实现轻量级Web服务器[原创]

浏览:3288次  出处信息

     由于最近要搞一个P2P项目,所以最近找了份C#版BtTorrent [MonoTorrent]代码,参考参考它对BT协议的实现,在看Tracker模块时发现了这个功能,非常不错,于是就将他单独挖出来,写了个简单测试代码,这东西还是很不错的,有时候还真能派上点用处。

    测试代码:

以下是代码片段:
    class Program
    {
        static HttpListener listener;

        public static bool Running
        {
            get { return listener != null; }
        }

        static void Main(string[] args)
        {
            Start();
            Console.WriteLine("正在监听中....");
            while (true)
            {
                System.Threading.Thread.Sleep(2000);
                
            }
            Console.WriteLine("IsOver");
            Console.ReadLine();
        }

        static void Start()
        {
            if (Running)
                return;

            listener = new HttpListener();
            //这里开启Http 监听
            listener.Prefixes.Add("http://127.0.0.1:1234/");//也支持域名形式
            listener.Start();
            //异步等待URL请求传入
            listener.BeginGetContext(EndGetRequest, listener); ;
        }

        static void Stop()
        {
            if (!Running)
                return;

            listener.Close();
            listener = null;
        }

        static void EndGetRequest(IAsyncResult result)
        {
            HttpListenerContext context = null;
            System.Net.HttpListener listener = (System.Net.HttpListener)result.AsyncState;

            try
            {
                context = listener.EndGetContext(result);
                HandleRequest(context);
            }
            catch (Exception ex)
            {
               Console.Write("Exception in listener: {0}{1}", Environment.NewLine, ex);
            }
            finally
            {
                if (context != null)
                    context.Response.Close();

                if (listener.IsListening)
                    listener.BeginGetContext(EndGetRequest, listener);
            }
        }

        static void HandleRequest(HttpListenerContext context)
        {
            bool isScrape = context.Request.RawUrl.StartsWith("/scrape", StringComparison.OrdinalIgnoreCase);

            string responseStr = "very nice! haha"n来个中文你支持吗?"n";
            for (int i = 0; i < context.Request.QueryString.Count; i++)
            {

                responseStr = responseStr + "query:" + context.Request.QueryString.Keys[i] + "=" + context.Request.QueryString[i] + ""n";
            }
            Console.WriteLine("good");

            byte[] response = System.Text.Encoding.Default.GetBytes(responseStr);
            context.Response.ContentType = "text/plain"; //这里的类型随便你写.如果想返回HTML格式使用text/html
            context.Response.StatusCode = 200;
            context.Response.ContentLength64 = response.LongLength;
            context.Response.OutputStream.Write(response, 0, response.Length);
        }
}

编译以上代码,运行编译生成出来的.exe文件,这时你的服务器上就开起了基与1234端口的http监听,此时你就可以通过 http://127.0.0.1:1234/?a=11&b=22 的地址格式来访问 该Web服务器了,很方便吧

建议继续学习:

  1. 移动互联网创业公司的服务器选择    (阅读:4770)
  2. 查看你服务器的安全性    (阅读:3115)
  3. Ruby作为服务器端应用已经成熟了    (阅读:2601)
  4. 图片服务器博客    (阅读:2439)
  5. Linux服务器基本安装    (阅读:2270)
  6. 一个使用PC服务器的高可用性方案介绍    (阅读:1938)
  7. 从零开始React服务器渲染    (阅读:1425)
QQ技术交流群:445447336,欢迎加入!
扫一扫订阅我的微信号:IT技术博客大学习
© 2009 - 2024 by blogread.cn 微博:@IT技术博客大学习

京ICP备15002552号-1