C#经验积累

编程入门 行业动态 更新时间:2024-10-25 02:30:07

C#<a href=https://www.elefans.com/category/jswz/34/1770055.html style=经验积累"/>

C#经验积累

点滴收获,成长源于足下的进步!

01,C#使用HttpListener创建最简易Http通讯服务器

1.简要介绍:
HttpListener是一种可以实现简易Http协议的侦听器,可以实现对Http协议( GET、HEAD、POST、PUT、DELETE、TRACE 或 OPTIONS)的监听并将处理的结果返回
2.常用属性:
MSDN介绍文档
-AuthenticationSchemes
说明:
对客户端进行身份验证的方式值为 AuthenticationSchemes的枚举值。 默认值是 Anonymous。
AuthenticationSchemes枚举值官方介绍:

      枚举值           索引值                 值含义Anonymous	    32768	          指定匿名身份验证。Basic       	8	   				      指定基本身份验证。Digest	        1	   			 	     指定摘要式身份验证。IntegratedWindowsAuthentication	    6	                  指定 Windows 身份验证。Negotiate	    2	                  和客户端协商以确定身份验证方案。 如果客户端和服务器均支持 Kerberos,则使用 Kerberos;否则使用 NTLM。None	    0	                   不允许进行任何身份验证。 设置了此标志并请求 HttpListener 对象的客户端将始终会接收 403 Forbidden 状态。 当资源决不应该用于客户端时,请使用此标志。Ntlm	    4	                   指定 NTLM 身份验证。
  • DefaultServiceNames
    说明:使用该属性中ServiceNameCollection的获取由已注册前缀确定的服务提供程序名 (SPN) 的默认列表。
  • IsListening
    说明:获取一个bool值,指示 HttpListener 是否已启动。
  • TimeoutManager
    说明:设置各种超时
  • Prefixes
    说明:获取当前HttpListener 对象在经配置后要处理的 URI 前缀。
  1. HttpListener创建步骤:
    Ⅰ,创建实例对象
    Ⅱ,添加监听的端口或url
    Ⅲ,启动监听
    Ⅳ,处理监听请求
    Ⅴ,停止监听
  2. 代码
  public class HttpService1{//使用单例模式创建监听实例对象private static HttpService1 service = null;public static HttpService1 CreateService{get{if (service == null){return new HttpService1();}else{return service;}}}HttpListener httpListener = null;//创建HttpListener实例bool isStarted = false;//获取实例的监听状态/// <summary>/// 获取服务状态/// </summary>public bool GetServiceStation { get { return isStarted; } }/// <summary>/// 开启服务/// </summary>/// <param name="service"></param>public void StarService(string ip,string port){try{if (httpListener != null){if (httpListener.IsListening){httpListener.Stop();}}else{httpListener = new HttpListener();}//   string url = $"http://{127.0.0.1}:{7000}/{AAA}/";//监听127.0.0.1:7000/AAA/服务接口的请求string url = $"http://{ip}:{port}/";httpListener = new HttpListener();//初始化实例httpListener.Prefixes.Add(url);//添加监听接口httpListener.Start();//启动httpListener.BeginGetContext(Result, null);//处理请求数据//isStarted = httpListener.IsListening;//获取服务监听状态}catch (Exception ex){throw new Exception($"创建{ip}:{port}服务失败!{Environment.NewLine}详细信息:{ex.Message}");}}/// <summary>/// 停止服务/// </summary>public void StopService(){httpListener.Close();isStarted = httpListener.IsListening;}/// <summary>/// 服务回调函数/// </summary>/// <param name="ar"></param>private void Result(IAsyncResult ar){if (!httpListener.IsListening)//如果服务已停止则直接终止{return;}//继续异步监听httpListener.BeginGetContext(Result, httpListener);lock (httpListener){if (httpListener.IsListening){//获得context对象var context = httpListener.EndGetContext(ar);var request = context.Request;//获取Request实例var response = context.Response;//获取Response实例Encoding encoding = context.Request.ContentEncoding;//获取请求的文本的编码格式//设置Request Http报文头context.Response.ContentType = string.Format("text/plain;charset={0}", encoding.BodyName);context.Response.AppendHeader("Access-Control-Allow-Origin", "*");context.Response.AppendHeader("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token");context.Response.AppendHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");context.Response.AppendHeader("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type");context.Response.AppendHeader("Access-Control-Allow-Credentials", "true");context.Response.ContentEncoding = encoding;//设置Request Http报文头编码格式ProcessRequest(request, response, encoding);}}}/// <summary>/// 处理请求数据/// </summary>/// <param name="request"></param>/// <param name="response"></param>/// <param name="encoding"></param>private void ProcessRequest(HttpListenerRequest request, HttpListenerResponse response, Encoding encoding){string ret = null;string apiUrI = request.RawUrl;//获取请求的接口路径(不包含服务IP和端口)switch (apiUrI)//根据请求接口路径进行处理{case "/AAA/":{ret = "AAA OK";}break;case "/BBB":{ret = "BBB OK";}break;}var returnByteArr = encoding.GetBytes(ret);//设置客户端返回信息的编码try{using (var stream = response.OutputStream)//创建response的输出实例{//把处理信息返回到客户端stream.Write(returnByteArr, 0, returnByteArr.Length);}}catch (Exception ex){throw new Exception("处理请求出现异常异常信息:" + ex.Message);}}}

水平有限,欢迎一起交流!!!

更多推荐

C#经验积累

本文发布于:2024-03-07 02:45:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1716628.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:经验

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!