返回顶部

收藏

C# 实现一个简单的 HTTP 服务器

更多
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;

class MainClass {
    private static int maxRequestHandlers = 5;
    private static int requestHandlerID = 0;
    private static HttpListener listener;
    private static void RequestHandler(IAsyncResult result) {
        try {
            HttpListenerContext context = listener.EndGetContext(result);
            StreamWriter sw = new StreamWriter(context.Response.OutputStream, Encoding.UTF8);
            sw.WriteLine("<html><head><title>C# </title>");
            sw.WriteLine("</head><body>" + result.AsyncState);
            sw.WriteLine("</body></html>");
            sw.Flush();

            context.Response.ContentType = "text/html";
            context.Response.ContentEncoding = Encoding.UTF8;

            context.Response.Close();
        } catch (ObjectDisposedException) {
            Console.WriteLine(result.AsyncState);
        } finally {
            if (listener.IsListening) {
                listener.BeginGetContext(RequestHandler, 
                    "RequestHandler_" + Interlocked.Increment(ref requestHandlerID));
            }
        }
    }

    public static void Main(string[] args) {
        using (listener = new HttpListener()) {
            listener.Prefixes.Add("http://localhost:8080/");
            listener.Start();
            for (int count = 0; count < maxRequestHandlers; count++) {
                listener.BeginGetContext(RequestHandler, "RequestHandler_" +
                    Interlocked.Increment(ref requestHandlerID));
            }
            Console.WriteLine("Press Enter to stop the HTTP Server");
            Console.ReadLine();
            listener.Stop();

            listener.Abort();
        }
    }
}
//该片段来自于http://outofmemory.cn

标签:c#,.net,网络

收藏

0人收藏

支持

0

反对

0

相关聚客文章
  1. Herb Sutter 发表 2012-08-02 11:26:37 “Strong” and “weak” hardware memory models
  2. dormy 发表 2013-12-12 02:28:41 c#.netDataGrid绑定数据库数据
  3. itcodes 发表 2014-07-22 17:00:00 C#计算时间差。
  4. 姚 广远 发表 2015-06-22 07:01:45 C++ 中的封送处理概述
  5. 姚 广远 发表 2015-06-22 07:01:45 C++ 中的封送处理概述
  6. 米豆网 - 1000seo 发表 2012-08-21 05:09:00 .netframework中TimeZoneInfo类的使用
  7. Herb Sutter 发表 2012-12-03 21:34:30 Perspective: “Why C++ Is Not ‘Back’”
  8. Herb Sutter 发表 2013-07-09 16:47:02 Recommended reading: Why mobile web apps are slow
  9. 姚 广远 发表 2015-04-15 05:20:48 C#语言规范—语句
  10. 姚 广远 发表 2015-04-13 02:54:10 C# 与 C++ 数据类型对照表
  11. 姚 广远 发表 2015-04-14 06:17:41 C# 语言规范 —类型、变量和值
  12. 姚 广远 发表 2015-04-13 05:03:47 .NET运行机制

发表评论