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

 

       由于最近要搞一个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服务器了,很方便吧

 

转载请写明出处,谢谢!

posted on 2009-04-03 14:36  优柔的和弦  阅读(...)  评论(...编辑  收藏

导航

统计