加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
HttpListener.cs 2.09 KB
一键复制 编辑 原始数据 按行查看 历史
bensenplus 提交于 2023-02-08 13:52 . temp
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.FileProviders;
namespace Xbrowser
{
public class HttpEventArgs
{
public string Command { get; }
public object Data { get; }
public HttpEventArgs(string command, object data) { Command = command; Data = data; }
}
public delegate void HttpEventHandler(object sender, HttpEventArgs e);
internal class HttpListener {
public event HttpEventHandler? OnRequest;
IWebHost? host;
public void Start()
{
Thread thread = new Thread(() =>
{
Run();
});
thread.Start();
}
public void Stop()
{
if(host!= null)
{
host.StopAsync();
}
}
public void Run()
{
int port = 2023;
host = new WebHostBuilder().UseKestrel((options) => {
options.ListenLocalhost(port);
}).Configure(app => {
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(Environment.CurrentDirectory),
RequestPath = "/static"
});
app.Run(RequestDelegate);
}).Build();
host.Run();
}
private Task RequestDelegate(HttpContext context)
{
try
{
if(context.Request.Method == "POST")
{
string command = context.Request.Path;
string data = context.Request.Form["data"];
OnRequest?.Invoke(this, new HttpEventArgs(command, data));
context.Response.Headers.AccessControlAllowOrigin = "*";
context.Response.WriteAsync(command);
}
return Task.CompletedTask;
}
catch (Exception ex)
{
return Task.FromException(ex);
}
}
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化