首页 > 其他分享 >HttpListener简单使用

HttpListener简单使用

时间:2023-01-12 19:34:13浏览次数:42  
标签:HttpMethod 简单 request httpMethod httpListener 使用 var HttpListener public

封装了一个简单便捷使用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         }

 

标签:HttpMethod,简单,request,httpMethod,httpListener,使用,var,HttpListener,public
From: https://www.cnblogs.com/xunyou/p/17047417.html

相关文章

  • Nexus私有maven库部署和使用
    原文地址:Nexus私有maven库部署和使用-Stars-One的杂货小窝前段圣诞节前后,Jitpack网站突然崩溃了,无法下载依赖,然后过了一个星期才解决了,好在没啥紧急的Android开发任务,......
  • 获取用户输入的用户和密码,然后使用封装后的jdbc来查库进行验证用户名和密码是否正确
    publicclassTest02{//获取用户输入的用户和密码,然后使用封装后的jdbc来查库进行验证用户名和密码是否正确publicstaticvoidmain(String[]args)throws......
  • Windows中sqlmap搭建(问题)和使用
    sqlmap搭建本次是win11和python11注意:SQLmap使用python写的,所以需要提前搭建好python环境.点击​​https://sqlmap.org/​​进入SQLmap的官网.点击下载压缩包,......
  • 支持数位板的远程软件,实现远程使用 Wacom 数位板
    现在数位板越来越流行了,影视、动漫、游戏、设计等行业经常需要用到。Wacom是数位板领域的全球领导者,其设备为创意人员带来了真正的纸感绘图体验。数位板用户需要远程办公的......
  • SpringBoot简单整合JPA
    SpringBoot简单整合JPAhttps://blog.csdn.net/qq_41378597/article/details/103444889最近帮朋友写个小项目,用惯了Mybatis,有机会想用下SpringBoot整合JPA,发现使用JPA......
  • Nginx基础01:安装和基本使用
    背景Nginx是一个高性能的Web服务器,几乎所有的Web服务都需要使用Nginx。关于Nginx的功能特性这里不再赘述,让我们从0开始,了解Nginx的基本用法,学习它在Web服务中都有哪些应......
  • Springboot简单整合JPA示例
    Springboot整合JPAhttps://blog.csdn.net/wdy00000/article/details/123588201文章目录JPA技术常用注解Springboot整合JPA1.引入JPA依赖2.配置3.启动类4.实体类5.......
  • 使用Stream进行List转Map踩坑Duplicate key错误
    报错代码myList.stream().collect(Collectors.toMap(MyDto::getCd,MyDto::getNm));报错信息java.lang.IllegalStateException:Duplicatekey000001-01-000000000000......
  • jdk8 stream使用
    匹配集合里面某个字段YthgkZdryHbhb=hbList.stream().filter(bo->!bo.getJz().equals(ythgkZdry.getJz())).collect(Collectors.toList()).get(0);将集合里面某个字段......
  • 为什么使用消息队列?
    理解:但是比较核心的有3个:解耦、异步、削峰解耦:A把数据放到MQ中,BCD需要就取,不需要就不取。A不用管BCD的需求异步:BCD会把数据存入对应的MQ,A可以直接取,可达到异步缩减时......