IT技术博客大学习 共学习 共进步
全部 移动开发 后端 数据库 AI 算法 安全 DevOps 前端 设计 开发者

通过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服务器了,很方便吧

同分类推荐文章

  1. 等了十年的 Go 链式管道,终于来了:seq 让你像写 Scala 一样写 Go (2026-06-25 18:38:18)
  2. Go 实验特性详解 (2026-06-21 10:05:27)
  3. amd64 微架构级别对 Go 程序性能提升多少? (2026-06-21 09:38:49)

查看更多 后端 文章 →

建议继续学习

  1. python实现一个P2P文件发布 (累计阅读 7,921)
  2. NAT连通性测试工具以及Flash P2P中的NAT穿透原理 (累计阅读 5,700)
  3. .NET 还是 Java? (累计阅读 5,655)
  4. 为什么国内还有那么多网站使用.NET架构? (累计阅读 5,243)
  5. C#和C++混合编程的一些tips (累计阅读 4,434)
  6. 设计模式速查手册-创建型 (累计阅读 3,922)
  7. p2p数据分发 (累计阅读 3,863)
  8. 什么是闭包(Closure)? (累计阅读 3,839)
  9. C#网络通信中中文字符的传送以及SQL数据库存取中文的解决方法 (累计阅读 3,305)
  10. PDC 2010:C#与Visual Basic的未来(上) (累计阅读 3,050)