C#通过HttpListener实现HTTP监听

Stella981
• 阅读 580

代码:

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
    }
}
点赞
收藏
评论区
推荐文章
待兔 待兔
3个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Stella981 Stella981
3年前
C# HTTPServer和OrleansClient结合
usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.IO.Compression;usingSystem.Linq;usingSystem.Net;usingSystem.Text;
Wesley13 Wesley13
3年前
C# 一个数组集合,任意组合,不遗漏,不重复
usingSystem;usingSystem.Collections.Generic;usingSystem.Diagnostics;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;names
Wesley13 Wesley13
3年前
C#调用打印机
usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Drawing;usingSystem.IO;usingSystem.Windows.Forms;namespaceTY\_ClassLibrary{  
Wesley13 Wesley13
3年前
Translater
usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Net;usingSystem.IO;usingNewtonsoft.Json;usingSystem.Web;
Stella981 Stella981
3年前
C#后台调用webapi
usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Linq;usingSystem.Net;usingSystem.Text;usingSystem.Threading.Tasks;
Wesley13 Wesley13
3年前
C# 实数矩阵行列式计算
原文链接: C实数矩阵行列式计算(https://my.oschina.net/ahaoboy/blog/775722)usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSy
Wesley13 Wesley13
3年前
C# 爬取图片
网络收集整理  爬取图片 引用AngleSharp NuGet包usingAngleSharp;usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Linq;usingSystem.Net
Stella981 Stella981
3年前
C# 调用windows时间同步服务获取准确时间
//创建一个Daytime类代码如下:usingSystem;usingSystem.Collections;usingSystem.Collections.Generic;usingSystem.Data;usingSystem.Diagnostics;usingSy
Wesley13 Wesley13
3年前
unity 测试加载本地文件
TestLoadXml.csusingUnityEngine;usingSystem.Collections;usingSystem.IO;usingSystem.Diagnostics;publicclassTestLoadXml:MonoBehaviour{