System.Net.HttpListener类(异步方式处理请求)

来源:互联网 发布:程序员 霸气 口号 编辑:程序博客网 时间:2024/04/29 04:27

class program
{
    static void Main()
    {

        System.Console.WriteLine(System.Net.HttpListener.IsSupported?"可用于本系统":"不可用于本系统");
        System.Net.HttpListener httplistener = new System.Net.HttpListener();
        string s = string.Format("http://localhost:8008/hello/");
        httplistener.Prefixes.Add(s);
        httplistener.Start();
        while (true)
        {
            System.Console.Title = string.Format("0代收集{0}次   1代收集{1}次 2代收集{2}次",
    System.GC.CollectionCount(0).ToString(),
    System.GC.CollectionCount(1).ToString(),
    System.GC.CollectionCount(2).ToString());

            System.IAsyncResult ia2 = httplistener.BeginGetContext(
                delegate(System.IAsyncResult ia)
                {
                    System.Net.HttpListener httplistener2 = ia.AsyncState as System.Net.HttpListener;
                    System.Net.HttpListenerContext hlc = httplistener2.EndGetContext(ia);
                    hlc.Response.ContentType = "text.html";
                    System.IO.StreamWriter sw = new System.IO.StreamWriter(
                        hlc.Response.OutputStream,
                        System.Text.Encoding.Default
                        );
                    sw.WriteLine("你好, 中国");
                    sw.Flush();
                    sw.Close();
                },
                httplistener
            );
            //System.Threading.Thread.Sleep(1000);
        }
    }
}