[C#]使用HttpListener实现简单的http服务器交互

业务需求:通过Http获取从客户端传来的信息并进行相应操作

public void HttpService()
    {
        try
        {
            WListener = new HttpListener();//新建Listener
            WListener.Prefixes.Add("http://localhost:8080/");//添加IP和端口
            WListener.Start();
            MessageBox.Show("启动成功!");
            int maxThreadNum, portThreadNum;

            //线程池
            int minThreadNum;
            ThreadPool.GetMaxThreads(out maxThreadNum, out portThreadNum);
            ThreadPool.GetMinThreads(out minThreadNum, out portThreadNum);
            while (true)
            {
                HttpListenerContext ctx = WListener.GetContext();
                ThreadPool.QueueUserWorkItem(new WaitCallback(ListenerHandle), ctx);
            }
        }
            catch (Exception ex)
            {
                MessageBox.Show(ex + "通讯器启动失败!");
            }
        }
       private void ListenerHandle(object o)
    	{
        HttpListenerContext ctx = (HttpListenerContext)o;
        ctx.Response.StatusCode = 200;//设置返回给客服端http状态代码

        string ID = ctx.Request.QueryString["id"];
        //string Name = ctx.Request.QueryString["name"];
        string Name = HttpUtility.ParseQueryString(ctx.Request.RawUrl).Get("name");

        //进行处理
        //MessageBox.Show(ID + Name);
        //使用Writer输出http响应代码
        using (StreamWriter writer = new StreamWriter(ctx.Response.OutputStream))
        {
            writer.Write("success!");
            writer.Close();
            ctx.Response.Close();
        }
        //操作函数
        xxxxxxxxxx
        }
    }

你可能感兴趣的:(C#,Http,通信)