C#模拟web服务器

来源:互联网 发布:淘宝客超级搜源码 编辑:程序博客网 时间:2024/05/02 06:11
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;


namespace CodeTest
{
    class Program
    {
        static void Main(string[] args)
        {
            using (HttpListener listerner = new HttpListener())
            {


                //添加监听地址,可以添加多个
                listerner.Prefixes.Add("http://127.0.0.1:8088/web/");


                listerner.Start();
                Console.WriteLine("web服务器已启动..");
                bool isListerner = true;//服务锁
                int count = 0;//客户段请求数量
                while (isListerner)
                {
                    //等待请求连接 没有请求则GetContext处于阻塞状态
                    HttpListenerContext ctx = listerner.GetContext();
                    Console.WriteLine("第" + (++count) + "次请求.");


                    ctx.Response.StatusCode = 200;//设置返回给客服端http状态代码


                    string name = ctx.Request.QueryString["name"];//客户端查询参数
                    if (name != null)
                    {
                        Console.WriteLine(name);
                    }




                    //使用Writer输出http响应代码
                    using (StreamWriter writer = new StreamWriter(ctx.Response.OutputStream))
                    {
                        writer.WriteLine("<html>");
                        writer.WriteLine(" <head>");
                        writer.WriteLine("  <meta http-equiv='content-type' content='text/html;charset=utf-8'>");
                        writer.WriteLine("  <title>c# web服务器</title>");
                        writer.WriteLine("</head>");


                        writer.WriteLine("<body>");
                        writer.WriteLine("  服务器响应:<br/>");
                        writer.WriteLine("  请求信息:<br/>");


                        //将请求头信息输出
                        foreach (string header in ctx.Request.Headers.Keys)
                        {
                            writer.WriteLine("  <b>{0}</b>={1}<br/>", header, ctx.Request.Headers[header]);
                        }
                        writer.WriteLine("</body>");
                        writer.WriteLine("</html>");
                        writer.Close();//关闭输出流
                        ctx.Response.Close();
                    }
                }
                listerner.Stop();
                Console.WriteLine("web服务器已关闭..");
            }
        }
    }

}