C# http服务端实例演示


  • 1. 创建http服务类 HttpServer.cs
  • using System;
  • using System.Collections.Generic;
  • using System.Linq;
  • using System.Net;
  • using System.Text;
  • using System.Threading.Tasks;
  • using System.Configuration;
  • using System.Threading;
  • using System.IO;
  • using Entities;
  • namespace Http_服务1
  • {
  •     /// <summary>
  •     /// http 监听 服务类
  •     /// </summary>
  •     public class HttpServer
  •     {
  •         /// <summary>
  •         /// http 监听器
  •         /// </summary>
  •         HttpListener _Listerner = null;
  •         /// <summary>
  •         /// 监听地址
  •         /// </summary>
  •         string _ListernUrl = string.Empty;
  •         /// <summary>
  •         /// 是否监听
  •         /// </summary>
  •         bool _IsRunning = false;
  •         /// <summary>
  •         /// 初始化
  •         /// </summary>
  •         public void Init()
  •         {
  •             _Listerner = new HttpListener();
  •             _IsRunning = true;
  •             if (System.Configuration.ConfigurationManager.AppSettings.AllKeys.Contains("lurl"))
  •             {
  •                 _ListernUrl = System.Configuration.ConfigurationManager.AppSettings["lurl"];
  •             }
  •             else
  •             {
  •                 _ListernUrl = "http://127.0.0.1:1500/Service/";
  •             }
  •         }
  •         /// <summary>
  •         /// 启动服务
  •         /// </summary>
  •         public void Start()
  •         {
  •             Init();
  •             try
  •             {
  •                 _Listerner.AuthenticationSchemes = AuthenticationSchemes.Anonymous;//指定身份验证 Anonymous匿名访问
  •                 _Listerner.Prefixes.Add(_ListernUrl);
  •                 //_listerner.Prefixes.Add("http://127.0.0.1:1500/Service/");
  •                 _Listerner.Start();
  •                 Console.WriteLine("服务器启动成功.......");
  •                 Task.Factory.StartNew(() =>
  •                 {
  •                     //线程池
  •                     int minThreadNum;
  •                     int portThreadNum;
  •                     int maxThreadNum;
  •                     ThreadPool.GetMaxThreads(out maxThreadNum, out portThreadNum);
  •                     ThreadPool.GetMinThreads(out minThreadNum, out portThreadNum);
  •                     Console.WriteLine("最大线程数:{0}", maxThreadNum);
  •                     Console.WriteLine("最小空闲线程数:{0}", minThreadNum);
  •                     //ThreadPool.QueueUserWorkItem(new WaitCallback(TaskProc1), x);
  •                     Console.WriteLine("\n\n等待客户连接中。。。。");
  •                     while (_IsRunning)
  •                     {
  •                         //等待请求连接
  •                         //没有请求则GetContext处于阻塞状态
  •                         HttpListenerContext ctx = _Listerner.GetContext();
  •                         ThreadPool.QueueUserWorkItem(new WaitCallback(TaskProc), ctx);
  •                     }
  •                     //listerner.Stop();
  •                 });
  •             }
  •             catch (Exception ex)
  •             {
  •                 Console.WriteLine("服务启动失败...");
  •                 return;
  •             }
  •         }
  •         private void TaskProc(object o)
  •         {
  •             HttpListenerContext ctx = (HttpListenerContext)o;
  •             ctx.Response.StatusCode = 200;//设置返回给客服端http状态代码
  •             #region http接收Get参数
  •             if (ctx.Request.HttpMethod=="GET")
  •             {
  •                 //接收Get参数
  •                 string type = ctx.Request.QueryString["type"];
  •                 string userId = ctx.Request.QueryString["userId"];
  •                 string password = ctx.Request.QueryString["password"];
  •                 string filename = Path.GetFileName(ctx.Request.RawUrl);
  •                 //string userName = HttpUtility.ParseQueryString(filename).Get("userName");//避免中文乱码
  •                 //进行处理
  •                 //Console.WriteLine("收到数据:" + userName);
  •             }
  •             #endregion
  •          
  •             #region http接收POST参数
  •             string receiveResult=string.Empty;
  •             if (ctx.Request.HttpMethod == "POST")
  •             {
  •                 //接收POST参数
  •                 Stream stream = ctx.Request.InputStream;
  •                 System.IO.StreamReader reader = new System.IO.StreamReader(stream, Encoding.UTF8);
  •                 String body = reader.ReadToEnd();
  •                 receiveResult=body.ToString();
  •                 List<LoginInfo> data = Newtonsoft.Json.JsonConvert.DeserializeObject<List<LoginInfo>>(receiveResult);
  •                 // Console.WriteLine("收到POST数据:" + HttpUtility.UrlDecode(body));
  •                 // Console.WriteLine("解析:" + HttpUtility.ParseQueryString(body).Get("userName"));
  •             
  •             }
  •             #endregion
  •             //使用Writer输出http响应代码,UTF8格式
  •             using (StreamWriter writer = new StreamWriter(ctx.Response.OutputStream, Encoding.UTF8))
  •             {
  •                 //writer.Write("处理结果,Hello world<br/>");
  •                 writer.Write(string.Format("后台收到的处理结果:  {0}<br/>", receiveResult));
  •                 //writer.Write("数据是userId={0},userName={1}", userId, userName);
  •                 writer.Close();
  •                 ctx.Response.Close();
  •             }
  •         }
  •     }
  • }

 

  • 2 . 启动http服务
  • using System;
  • using System.Collections.Generic;
  • using System.IO;
  • using System.Linq;
  • using System.Net;
  • using System.Text;
  • using System.Threading;
  • using System.Threading.Tasks;
  • namespace Http_服务1
  • {
  •     class Program
  •     {
  •         static void Main(string[] args)
  •         {
  •             HttpServer httpServer = new HttpServer();
  •             httpServer.Start();
  •             Console.Read();
  •         }
  •         
  •     }
  • }

using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Text;using System.Threading.Tasks;using System.Configuration;using System.Threading;using System.IO;using Entities;
namespace Http_服务1{    /// <summary>    /// http 监听 服务类    /// </summary>    public class HttpServer    {        /// <summary>        /// http 监听器        /// </summary>        HttpListener _Listerner = null;
        /// <summary>        /// 监听地址        /// </summary>        string _ListernUrl = string.Empty;
        /// <summary>        /// 是否监听        /// </summary>        bool _IsRunning = false;
        /// <summary>        /// 初始化        /// </summary>        public void Init()        {            _Listerner = new HttpListener();            _IsRunning = true;            if (System.Configuration.ConfigurationManager.AppSettings.AllKeys.Contains("lurl"))            {                _ListernUrl = System.Configuration.ConfigurationManager.AppSettings["lurl"];            }            else            {                _ListernUrl = "http://127.0.0.1:1500/Service/";            }        }
        /// <summary>        /// 启动服务        /// </summary>        public void Start()        {            Init();            try            {                _Listerner.AuthenticationSchemes = AuthenticationSchemes.Anonymous;//指定身份验证 Anonymous匿名访问                _Listerner.Prefixes.Add(_ListernUrl);                //_listerner.Prefixes.Add("http://127.0.0.1:1500/Service/");                _Listerner.Start();                Console.WriteLine("服务器启动成功.......");
                Task.Factory.StartNew(() =>                {                    //线程池                    int minThreadNum;                    int portThreadNum;                    int maxThreadNum;                    ThreadPool.GetMaxThreads(out maxThreadNum, out portThreadNum);                    ThreadPool.GetMinThreads(out minThreadNum, out portThreadNum);                    Console.WriteLine("最大线程数:{0}", maxThreadNum);                    Console.WriteLine("最小空闲线程数:{0}", minThreadNum);                    //ThreadPool.QueueUserWorkItem(new WaitCallback(TaskProc1), x);
                    Console.WriteLine("\n\n等待客户连接中。。。。");                    while (_IsRunning)                    {                        //等待请求连接                        //没有请求则GetContext处于阻塞状态                        HttpListenerContext ctx = _Listerner.GetContext();
                        ThreadPool.QueueUserWorkItem(new WaitCallback(TaskProc), ctx);                    }                    //listerner.Stop();
                });
            }            catch (Exception ex)            {                Console.WriteLine("服务启动失败...");                return;            }        }

        private void TaskProc(object o)        {            HttpListenerContext ctx = (HttpListenerContext)o;
            ctx.Response.StatusCode = 200;//设置返回给客服端http状态代码
            #region http接收Get参数            if (ctx.Request.HttpMethod=="GET")            {                //接收Get参数                string type = ctx.Request.QueryString["type"];                string userId = ctx.Request.QueryString["userId"];                string password = ctx.Request.QueryString["password"];                string filename = Path.GetFileName(ctx.Request.RawUrl);                //string userName = HttpUtility.ParseQueryString(filename).Get("userName");//避免中文乱码                //进行处理                //Console.WriteLine("收到数据:" + userName);            }            #endregion         
            #region http接收POST参数            string receiveResult=string.Empty;            if (ctx.Request.HttpMethod == "POST")            {                //接收POST参数                Stream stream = ctx.Request.InputStream;                System.IO.StreamReader reader = new System.IO.StreamReader(stream, Encoding.UTF8);                String body = reader.ReadToEnd();                receiveResult=body.ToString();                List<LoginInfo> data = Newtonsoft.Json.JsonConvert.DeserializeObject<List<LoginInfo>>(receiveResult);
                // Console.WriteLine("收到POST数据:" + HttpUtility.UrlDecode(body));                // Console.WriteLine("解析:" + HttpUtility.ParseQueryString(body).Get("userName"));                        }            #endregion
            //使用Writer输出http响应代码,UTF8格式            using (StreamWriter writer = new StreamWriter(ctx.Response.OutputStream, Encoding.UTF8))            {                //writer.Write("处理结果,Hello world<br/>");                writer.Write(string.Format("后台收到的处理结果:  {0}<br/>", receiveResult));                //writer.Write("数据是userId={0},userName={1}", userId, userName);                writer.Close();                ctx.Response.Close();            }
        }

    }}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM