C#通过HttpListener实现HTTP监听

代码:

1using NLog; 2using System; 3using System.Diagnostics; 4using System.IO; 5using System.Net; 6using System.ServiceProcess; 7using System.Text; 8using System.Threading; 9using System.Web; 10using System.Xml; 11 12namespace MasterCardService 13{ 14 public partial class MainService : ServiceBase 15 { 16 private static Logger logger = LogManager.GetCurrentClassLogger(); 17 private HttpListener MyListerner; 18 19 public MainService() 20 { 21 InitializeComponent(); 22 } 23 24 public void DebugStart() 25 { 26 OnStart(null); 27 } 28 29 protected override void OnStart(string[] args) 30 { 31 MyListerner = new HttpListener(); 32 while (true) 33 { 34 try 35 { 36 MyListerner.AuthenticationSchemes = AuthenticationSchemes.Anonymous; 37 MyListerner.Prefixes.Add("http://127.0.0.1:7788/Service/"); 38 MyListerner.Start(); 39 } 40 catch (Exception ex) 41 { 42 logger.Error(ex, "服务器启动失败......"); 43 break; 44 } 45 logger.Debug("服务器启动成功......"); 46 47 //线程池 48 int minThreadNum; 49 int portThreadNum; 50 int maxThreadNum; 51 ThreadPool.GetMaxThreads(out maxThreadNum, out portThreadNum); 52 ThreadPool.GetMinThreads(out minThreadNum, out portThreadNum); 53 logger.Debug("最大线程数:{0}", maxThreadNum); 54 logger.Debug("最小空闲线程数:{0}", minThreadNum); 55 //ThreadPool.QueueUserWorkItem(new WaitCallback(TaskProc1), x); 56 57 logger.Debug("\n等待客户连接中......"); 58 while (true) 59 { 60 //等待请求连接 61 //没有请求则GetContext处于阻塞状态 62 HttpListenerContext ctx = MyListerner.GetContext(); 63 64 ThreadPool.QueueUserWorkItem(new WaitCallback(TaskProc), ctx); 65 } 66 } 67 } 68 69 protected override void OnStop() 70 { 71 MyListerner?.Stop(); 72 } 73 74 void TaskProc(object obj) 75 { 76 HttpListenerContext ctx = (HttpListenerContext)obj; 77 78 ctx.Response.StatusCode = 200;//设置返回给客服端http状态代码 79 80 //接收POST参数 81 Stream stream = ctx.Request.InputStream; 82 System.IO.StreamReader reader = new System.IO.StreamReader(stream, Encoding.UTF8); 83 string body = reader.ReadToEnd(); 84 logger.Debug("收到POST数据:\r\n" + HttpUtility.UrlDecode(body)); 85 86 var replyMsg = ProcessMessage(body); 87 88 //使用Writer输出http响应代码,UTF8格式 89 using (StreamWriter writer = new StreamWriter(ctx.Response.OutputStream, Encoding.UTF8)) 90 { 91 writer.Write(replyMsg); 92 writer.Close(); 93 ctx.Response.Close(); 94 } 95 } 96 97 private string ProcessMessage(string body) 98 { 99 XmlDocument recvDoc = new XmlDocument(); 100 recvDoc.LoadXml(body); 101 XmlNode recvRoot = recvDoc.SelectSingleNode("Msg"); 102 var firstChild = recvRoot.FirstChild; 103 104 XmlDocument sendDoc = CreateXmlDocument(); 105 XmlElement sendRoot = CreateRootElement(sendDoc); 106 sendDoc.AppendChild(sendRoot); 107 108 switch (firstChild.Name) 109 { 110 case "AgentInfoSet": 111 { 112 XmlElement returnNode = CreateReturnElement(sendDoc, firstChild.Name); 113 sendRoot.AppendChild(returnNode); 114 break; 115 } 116 case "GetAgentInfo": 117 { 118 XmlElement returnNode = CreateReturnElement(sendDoc, firstChild.Name); 119 sendRoot.AppendChild(returnNode); 120 121 XmlElement returnInfoNode = sendDoc.CreateElement("ReturnInfo"); 122 sendRoot.AppendChild(returnInfoNode); 123 break; 124 } 125 default: 126 Debug.Assert(false); 127 break; 128 } 129 130 return sendDoc.InnerXml; 131 } 132 133 #region 生成XML数据 134 private XmlElement CreateReturnElement(XmlDocument doc, string name) 135 { 136 XmlElement node = doc.CreateElement("Return"); 137 node.SetAttribute("Type", name); 138 node.SetAttribute("Value", "0"); 139 node.SetAttribute("Desc", "成功"); 140 141 return node; 142 } 143 144 private XmlElement CreateRootElement(XmlDocument doc) 145 { 146 XmlElement root = doc.CreateElement("Msg"); 147 root.SetAttribute("Version", "3.0"); 148 root.SetAttribute("MsgID", "2"); 149 root.SetAttribute("Type", "MonUp"); 150 root.SetAttribute("DateTime", DateTime.Now.ToString()); 151 root.SetAttribute("SrcCode", "110000D01"); 152 root.SetAttribute("DstCode", "110000G01"); 153 root.SetAttribute("ReplyID", "1000_ID"); 154 155 return root; 156 } 157 158 private XmlDocument CreateXmlDocument() 159 { 160 XmlDocument doc = new XmlDocument(); 161 XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "GB2312", "yes"); 162 doc.AppendChild(dec); 163 164 return doc; 165 } 166 #endregion 167 } 168}
点赞
收藏

评论区

加载中...

相关推荐

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

C# HTTPServer和OrleansClient结合

usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.IO.Compression;usingSystem.Linq;usingSystem.Net;usingSystem.Text;

C# 一个数组集合,任意组合,不遗漏,不重复

usingSystem;usingSystem.Collections.Generic;usingSystem.Diagnostics;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;names

C#调用打印机

usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Drawing;usingSystem.IO;usingSystem.Windows.Forms;namespaceTY\_ClassLibrary{  

Translater

usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Net;usingSystem.IO;usingNewtonsoft.Json;usingSystem.Web;

C#后台调用webapi

usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Linq;usingSystem.Net;usingSystem.Text;usingSystem.Threading.Tasks;

C#通过HttpListener实现HTTP监听 - HelloWorld