C#通过HttpListener实现HTTP监听

2021-06-21 19:03

阅读:473

标签:ssl   inpu   efi   []   onstop   响应   str   call   失败   

代码:

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
    }
}

 

C#通过HttpListener实现HTTP监听

标签:ssl   inpu   efi   []   onstop   响应   str   call   失败   

原文地址:https://www.cnblogs.com/wzwyc/p/10229182.html


评论


亲,登录后才可以留言!