HttpListener简单使用

封装了一个简单便捷使用HttpListener的类,可直接添加接口,实现处理逻辑。

  1 using System;
  2 using System.Collections.Concurrent;
  3 using System.Collections.Generic;
  4 using System.Net;
  5 
  6 namespace Common.Toolkit
  7 {
  8     public enum HttpMethod
  9     {
 10         Get, Post, Put
 11     }
 12 
 13     /// <summary>
 14     /// Http服务类,提供Get/Post请求处理逻辑
 15     /// </summary>
 16     internal class HttpListenerServer
 17     {
 18         HttpListener _httpListener;
 19         string _url;
 20         ConcurrentDictionary<string, List<Action<HttpMethod, HttpListenerRequest, HttpListenerResponse>>> _dicPrefixesActions = new ConcurrentDictionary<string, List<Action<HttpMethod, HttpListenerRequest, HttpListenerResponse>>>();
 21         Action<string> _errorActionHandle = null;
 22         public HttpListenerServer(uint port)
 23         {
 24             _httpListener = new HttpListener();
 25             var ipAddress = GetLocalIpAddress();
 26             _url = $"http://{ipAddress}:{port}";
 27         }
 28 
 29         /// <summary>
 30         /// 添加出错处理
 31         /// </summary>
 32         /// <param name="errorAction"></param>
 33         public void AddErrorListener(Action<string> errorAction)
 34         {
 35             _errorActionHandle = errorAction;
 36         }
 37 
 38         /// <summary>
 39         /// 添加侦听接口,以/开始,以/结束
 40         /// </summary>
 41         /// <param name="method"></param>
 42         /// <param name="action"></param>
 43         public void AddPrefixes(string method, Action<HttpMethod, HttpListenerRequest, HttpListenerResponse> action)
 44         {
 45             if (_dicPrefixesActions.TryGetValue(method, out var actions))
 46             {
 47                 actions.Add(action);
 48             }
 49             else
 50             {
 51                 _dicPrefixesActions.TryAdd(method, new List<Action<HttpMethod, HttpListenerRequest, HttpListenerResponse>>() { action });
 52             }
 53             _httpListener.Prefixes.Add(_url + method);
 54         }
 55 
 56         public bool StartListen()
 57         {
 58             bool isStart = false;
 59             try
 60             {
 61                 _httpListener.Start();
 62                 _httpListener.BeginGetContext(Revieve, null);
 63                 isStart = true;
 64             }
 65             catch (Exception ex)
 66             {
 67                 _errorActionHandle?.Invoke($"StartListen Error!Msg:{ex.Message}");
 68             }
 69             return isStart;
 70         }
 71 
 72         /// <summary>
 73         /// 处理请求
 74         /// </summary>
 75         /// <param name="ar"></param>
 76         private void Revieve(IAsyncResult ar)
 77         {
 78             try
 79             {
 80                 if (!_httpListener.IsListening) { return; }
 81                 _httpListener.BeginGetContext(Revieve, null);
 82                 var context = _httpListener.EndGetContext(ar);//获得Context对象
 83                 var request = context.Request;
 84                 var response = context.Response;
 85                 HttpMethod httpMethod = HttpMethod.Get;
 86                 switch (request.HttpMethod.ToLower())
 87                 {
 88                     case "post":
 89                         httpMethod = HttpMethod.Post;
 90                         break;
 91                     case "get":
 92                         httpMethod = HttpMethod.Get;
 93                         break;
 94                     case "put":
 95                         httpMethod = HttpMethod.Post;
 96                         break;
 97                     default:
 98                         break;
 99                 }
100                 if (_dicPrefixesActions.TryGetValue(request.RawUrl, out var actions))
101                 {
102                     foreach (var item in actions)
103                     {
104                         item.Invoke(httpMethod, request, response);
105                     }
106                 }
107             }
108             catch (Exception ex) 
109             {
110                 _errorActionHandle?.Invoke($"Revieve Error!Msg:{ex.Message}");
111             }
112         }
113 
114         public void Dispose()
115         {
116             _httpListener.Stop();
117             _httpListener.Close();
118             _httpListener = null;
119         }
120 
121         /// <summary>
122         /// 获得本地ip
123         /// </summary>
124         /// <returns></returns>
125         string GetLocalIpAddress()
126         {
127             string name = Dns.GetHostName();
128             IPAddress[] iPAddresseList = Dns.GetHostAddresses(name);
129             string ipAddress = "";
130             foreach (var item in iPAddresseList)
131             {
132                 if (item.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
133                 {
134                     ipAddress = item.ToString();
135                     break;
136                 }
137             }
138             return ipAddress;
139         }
140     }
141 }

使用如下:

 1  public void DoTest()
 2         {
 3             HttpListenerServer httpListenerServer = new HttpListenerServer(8082);
 4             httpListenerServer.AddErrorListener((errMsg) =>
 5             {
 6                 //出错处理
 7             });
 8             httpListenerServer.AddPrefixes("/getTest/", (httpMethod, request, response) =>
 9             {
10                 //处理请求逻辑
11             });
12             httpListenerServer.AddPrefixes("/postTest/", (httpMethod, request, response) =>
13             {
14                 //处理请求逻辑
15             });
16             bool ret = httpListenerServer.StartListen();//开始侦听
17         }

 

posted @ 2023-01-12 19:15  荀幽  阅读(235)  评论(0编辑  收藏  举报