C#分类辅助类:监听http请求

30 篇文章 1 订阅
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Wsfly
{
    /// <summary>
    /// 监听Http
    /// </summary>
    public class WsHttpListener
    {
        /*
         * DEMO:
         * 注册请求事件
         * WsHttpListener.HandleRequest_Event += WsHttpListener_HandleRequest_Event;
         * WsHttpListener.Start("http://192.168.1.100:8080/");
         * 
         * //处理事件
            private string WsHttpListener_HandleRequest_Event(System.Net.HttpListenerRequest request, System.Net.HttpListenerResponse response)
            {
                string id = request.QueryString["id"];
                return "收到ID:" + id;
            }
         */

        /// <summary>
        /// HTTP监听器
        /// </summary>
        private static HttpListener _httpListener;

        /// <summary>
        /// 处理请求委托
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        /// <returns></returns>
        public delegate string HandleRequest_Delegate(HttpListenerRequest request, HttpListenerResponse response);
        /// <summary>
        /// 处理请求事件
        /// </summary>
        public static event HandleRequest_Delegate HandleRequest_Event;

        /// <summary>
        /// 开始监听
        /// </summary>
        /// <param name="uri">监听地址 如:http://192.168.1.100:8080/ </param>
        public static void Start(string uri)
        {
            try
            {
                //HTTP 协议侦听器
                _httpListener = new HttpListener();
                //定义url及端口号
                _httpListener.Prefixes.Add(uri);
                //启动监听器
                _httpListener.Start();

                //异步监听客户端请求,当客户端的网络请求到来时会自动执行Result委托
                //该委托没有返回值,有一个IAsyncResult接口的参数,可通过该参数获取context对象
                _httpListener.BeginGetContext(ReceiveRequest, null);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 接收到网络请求
        /// </summary>
        /// <param name="ar"></param>
        private static void ReceiveRequest(IAsyncResult ar)
        {
            try
            {
                //继续异步监听
                _httpListener.BeginGetContext(ReceiveRequest, null);

                //获得context对象
                var context = _httpListener.EndGetContext(ar);
                var request = context.Request;
                var response = context.Response;

                如果是js的ajax请求,还可以设置跨域的ip地址与参数
                //context.Response.AppendHeader("Access-Control-Allow-Origin", "*");//后台跨域请求,通常设置为配置文件
                //context.Response.AppendHeader("Access-Control-Allow-Headers", "ID,PW");//后台跨域参数设置,通常设置为配置文件
                //context.Response.AppendHeader("Access-Control-Allow-Method", "post");//后台跨域请求设置,通常设置为配置文件

                //context.Response.ContentType = "text/plain;charset=UTF-8";//告诉客户端返回的ContentType类型为纯文本格式,编码为UTF-8
                //context.Response.AddHeader("Content-type", "text/plain");//添加响应头信息

                context.Response.ContentType = "application/json;charset=UTF-8";
                context.Response.AddHeader("Content-type", "application/json");

                context.Response.ContentEncoding = Encoding.UTF8;

                try
                {
                    //处理请求
                    string result = HandleRequest_Event?.Invoke(request, response);
                    if (!string.IsNullOrWhiteSpace(result))
                    {
                        response.StatusDescription = "200";
                        response.StatusCode = 200;
                        
                        //输出JSON
                        var resultByteArr = Encoding.UTF8.GetBytes(result);
                        using (var stream = response.OutputStream)
                        {
                            //把处理信息返回到客户端
                            stream.Write(resultByteArr, 0, resultByteArr.Length);
                        }
                    }
                    else
                    {
                        response.StatusDescription = "404";
                        response.StatusCode = 404;
                    }
                }
                catch (Exception ex)
                {
                    response.StatusDescription = "500";
                    response.StatusCode = 500;
                }
            }
            catch (Exception ex)
            {
                //处理异常
            }
        }
    }
}

调用方法:

WsHttpListener.HandleRequest_Event += WsHttpListener_HandleRequest_Event;

WsHttpListener.Start("http://192.168.1.100:8080/");

/// <summary>

/// 收到请求时处理事件

/// </summary>

/// <param name="request"></param>

/// <param name="response"></param>

/// <returns></returns>

private string WsHttpListener_HandleRequest_Event(System.Net.HttpListenerRequest request, System.Net.HttpListenerResponse response)

{

string id = request.QueryString["id"];

return "收到ID:" + id;

}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MOZ-Soft

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值