编程语言
首页 > 编程语言> > C#通过HttpListener实现HTTP监听

C#通过HttpListener实现HTTP监听

作者:互联网

代码

using NLog;
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Web;
using System.Xml;

namespace MasterCardService
{
    public partial class MainService : ServiceBase
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();
        private HttpListener MyListerner;

        public MainService()
        {
            InitializeComponent();
        }

        public void DebugStart()
        {
            OnStart(null);
        }

        protected override void OnStart(string[] args)
        {
            MyListerner = new HttpListener();
            while (true)
            {
                try
                {
                    MyListerner.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
                    MyListerner.Prefixes.Add("http://127.0.0.1:7788/Service/");
                    MyListerner.Start();
                }
                catch (Exception ex)
                {
                    logger.Error(ex, "服务器启动失败......");
                    break;
                }
                logger.Debug("服务器启动成功......");

                //线程池
                int minThreadNum;
                int portThreadNum;
                int maxThreadNum;
                ThreadPool.GetMaxThreads(out maxThreadNum, out portThreadNum);
                ThreadPool.GetMinThreads(out minThreadNum, out portThreadNum);
                logger.Debug("最大线程数:{0}", maxThreadNum);
                logger.Debug("最小空闲线程数:{0}", minThreadNum);
                //ThreadPool.QueueUserWorkItem(new WaitCallback(TaskProc1), x);

                logger.Debug("\n等待客户连接中......");
                while (true)
                {
                    //等待请求连接
                    //没有请求则GetContext处于阻塞状态
                    HttpListenerContext ctx = MyListerner.GetContext();

                    ThreadPool.QueueUserWorkItem(new WaitCallback(TaskProc), ctx);
                }
            }
        }

        protected override void OnStop()
        {
            MyListerner?.Stop();
        }

        void TaskProc(object obj)
        {
            HttpListenerContext ctx = (HttpListenerContext)obj;

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

            //接收POST参数
            Stream stream = ctx.Request.InputStream;
            System.IO.StreamReader reader = new System.IO.StreamReader(stream, Encoding.UTF8);
            string body = reader.ReadToEnd();
            logger.Debug("收到POST数据:\r\n" + HttpUtility.UrlDecode(body));

            var replyMsg = ProcessMessage(body);

            //使用Writer输出http响应代码,UTF8格式
            using (StreamWriter writer = new StreamWriter(ctx.Response.OutputStream, Encoding.UTF8))
            {
                writer.Write(replyMsg);
                writer.Close();
                ctx.Response.Close();
            }
        }

        private string ProcessMessage(string body)
        {
            XmlDocument recvDoc = new XmlDocument();
            recvDoc.LoadXml(body);
            XmlNode recvRoot = recvDoc.SelectSingleNode("Msg");
            var firstChild = recvRoot.FirstChild;

            XmlDocument sendDoc = CreateXmlDocument();
            XmlElement sendRoot = CreateRootElement(sendDoc);
            sendDoc.AppendChild(sendRoot);

            switch (firstChild.Name)
            {
                case "AgentInfoSet":
                    {
                        XmlElement returnNode = CreateReturnElement(sendDoc, firstChild.Name);
                        sendRoot.AppendChild(returnNode);
                        break;
                    }
                case "GetAgentInfo":
                    {
                        XmlElement returnNode = CreateReturnElement(sendDoc, firstChild.Name);
                        sendRoot.AppendChild(returnNode);

                        XmlElement returnInfoNode = sendDoc.CreateElement("ReturnInfo");
                        sendRoot.AppendChild(returnInfoNode);
                        break;
                    }
                default:
                    Debug.Assert(false);
                    break;
            }

            return sendDoc.InnerXml;
        }

        #region 生成XML数据
        private XmlElement CreateReturnElement(XmlDocument doc, string name)
        {
            XmlElement node = doc.CreateElement("Return");
            node.SetAttribute("Type", name);
            node.SetAttribute("Value", "0");
            node.SetAttribute("Desc", "成功");

            return node;
        }

        private XmlElement CreateRootElement(XmlDocument doc)
        {
            XmlElement root = doc.CreateElement("Msg");
            root.SetAttribute("Version", "3.0");
            root.SetAttribute("MsgID", "2");
            root.SetAttribute("Type", "MonUp");
            root.SetAttribute("DateTime", DateTime.Now.ToString());
            root.SetAttribute("SrcCode", "110000D01");
            root.SetAttribute("DstCode", "110000G01");
            root.SetAttribute("ReplyID", "1000_ID");

            return root;
        }

        private XmlDocument CreateXmlDocument()
        {
            XmlDocument doc = new XmlDocument();
            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "GB2312", "yes");
            doc.AppendChild(dec);

            return doc;
        }
        #endregion
    }
}

转载自https://www.cnblogs.com/wzwyc/p/10229182.html

标签:HTTP,C#,XmlDocument,SetAttribute,System,XmlElement,HttpListener,using,root
来源: https://www.cnblogs.com/xiaoxiongblog123/p/15463682.html