c#使用HttpListener监听HTTP请求
·
【官方介绍】:Windows XP SP2 or Server 2003 is required to use the HttpListener class.
在win10上执行没问题,在winform和console开启一个小型的http请求(小型API)
/// <summary>
/// http 监听服务
/// </summary>
public class HttpListenHelper
{
/// <summary>
/// 监听服务
/// </summary>
private static HttpListener _httpListener;
/// <summary>
/// 构造函数
/// </summary>
public HttpListenHelper()
{
Start();
}
/// <summary>
/// 开启监听
/// </summary>
public void Start()
{
if (_httpListener == null || !_httpListener.IsListening)
{
//获取本机IP
IPHostEntry ipEntry = Dns.GetHostEntry(Dns.GetHostName());
string strIp = "localhost";
foreach (var ip in ipEntry.AddressList)
{
if (!ip.IsIPv6LinkLocal)
{
strIp = ip.ToString();
break;
}
}
// 结尾别少了'/'
string _url = $"http://{strIp}:9999/";
_httpListener = new HttpListener();
_httpListener.Prefixes.Add(_url);
_httpListener.Start();
_httpListener.BeginGetContext(GetContextCallBack, _httpListener);
}
}
/// <summary>
/// 回调
/// </summary>
/// <param name="ar"></param>
/// <exception cref="ArgumentException"></exception>
private void GetContextCallBack(IAsyncResult res)
{
try
{
HttpListener _listener = res.AsyncState as HttpListener;
if (_listener.IsListening)
{
HttpListenerContext context = _listener.EndGetContext(res);
_listener.BeginGetContext(GetContextCallBack, _listener); // 继续建立请求回调
//解析http请求
HttpListenerRequest request = context.Request;
string rawUrl = request.RawUrl.ToLower();
//获取传递的请求数据
var reader = new StreamReader(request.InputStream, Encoding.UTF8);
string json = reader.ReadToEnd();
// 获取返回的数据
object? obj = GetTable();
OutResult(context, obj);
}
}
catch (Exception ex)
{
WriteLog.Write(ex.Message, ex.StackTrace!);
}
}
/// <summary>
/// 输出结果
/// </summary>
/// <param name="context"></param>
/// <param name="json"></param>
/// <param name="intStatus "></param>
private void OutResult(HttpListenerContext context, object obj, int intStatus = 200)
{
HttpListenerResponse response = context.Response;
response.StatusCode = intStatus;
response.ContentType = "application/json;charset=UTF-8";
response.ContentEncoding = Encoding.UTF8;
response.AppendHeader("Content-Type", "application/json;charset=UTF-8");
string json = JsonSerializer.Serialize(obj);
using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8))
{
writer.Write(json);
writer.Close();
response.Close();
}
}
/// <summary>
/// 停止
/// </summary>
public void Stop()
{
if (_httpListener != null && _httpListener.IsListening)
{
_httpListener.Stop();
_httpListener.Close();
_httpListener = null!;
}
}
~HttpListenHelper()
{
Stop();
}
}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)