This commit is contained in:
CortexCore
2023-10-02 23:24:56 +08:00
parent 8ef5c7ec0a
commit 947e52e748
183 changed files with 107857 additions and 9378 deletions

View File

@@ -0,0 +1,15 @@
using System;
using System.Net;
using System.Net.Http;
namespace BITKit.Net.Http
{
public interface IHttpListenerService
{
bool IsListening { get; }
int Port { get; set; }
public event Func<HttpListenerRequest,HttpContent> OnRequest;
void Start();
void Stop();
}
}

View File

@@ -0,0 +1,105 @@
using System;
using System.Net;
using System.Net.Http;
using System.Threading;
namespace BITKit.Net.Http
{
public class HttpListenerService:IHttpListenerService
{
public bool IsListening=>_httpListener.IsListening;
public int Port { get; set; }
private readonly HttpListener _httpListener = new();
public event Func<HttpListenerRequest,HttpContent> OnRequest;
private readonly CancellationTokenSource _cancellationTokenSource = new();
private CancellationToken _cancellationToken=>_cancellationTokenSource.Token;
public HttpListenerService()
{
Port = 7001;
}
public HttpListenerService(int port)
{
Port = port;
}
public void Start()
{
if (HttpListener.IsSupported is false)
{
throw new NotImplementedException("HttpListener is not supported this platform");
}
_httpListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
//_httpListener.Prefixes.Add($"http://localhost:{Port}/");
#if NET5_0_OR_GREATER
_httpListener.Prefixes.Add($"http://localhost:{Port}/");
#else
_httpListener.Prefixes.Add($"http://*:{Port}/");
#endif
Thread thread = new(Process);
thread.Start();
}
public void Stop()
{
_cancellationTokenSource.Cancel();
_httpListener.Stop();
BIT4Log.Log<IHttpListenerService>("Is Trying To Stop");
}
private void Process()
{
_httpListener.Start();
BIT4Log.Log<IHttpListenerService>($"{Port}\tIs Listening");
while (_cancellationToken.IsCancellationRequested is false)
{
var result = _httpListener.BeginGetContext(ListenerCallback, _httpListener);
result.AsyncWaitHandle.WaitOne();
}
BIT4Log.Log<IHttpListenerService>($"{Port}\tStopped");
}
private void ListenerCallback(IAsyncResult result)
{
if (_cancellationToken.IsCancellationRequested) return;
var context = _httpListener.EndGetContext(result);
var request = context.Request;
var response = context.Response;
var output = response.OutputStream;
if (request.RawUrl is "/favicon.ico")
{
output.Close();
response.Close();
return;
}
// 启用CORS
response.Headers.Add("Access-Control-Allow-Origin", "*"); // 允许任何来源访问,生产环境应更具体设置
response.Headers.Add("Access-Control-Allow-Methods", "*"); // 允许的HTTP方法
response.Headers.Add("Access-Control-Allow-Headers", "*"); // 允许的标头
var content = OnRequest?.Invoke(request);
var buffer = StringHelper.GetBytes(ContextModel.Error("没有注册请求事件"));
if (content is not null)
{
#if NET5_0_OR_GREATER
buffer = content!.ReadAsByteArrayAsync(_cancellationToken).Result;
#else
buffer = content!.ReadAsByteArrayAsync().Result;
#endif
}
response.ContentLength64 = buffer.Length;
output.Write(buffer);
output.Close();
response.Close();
}
}
}

View File

@@ -0,0 +1,16 @@
using System;
using System.Net;
namespace BITKit.Net.LAN
{
public interface ILANBroadcaster
{
int Port { get; set; }
byte[] Buffer { get; set; }
event Action<EndPoint, string> OnReceive;
void StartBroadcast();
void StopBroadcast();
void StartListen();
void StopListen();
}
}

View File

@@ -0,0 +1,108 @@
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace BITKit.Net.LAN
{
/// <summary>
/// 基于UDP的LAN广播
/// </summary>
public class UdpBasedLanBroadcaster : ILANBroadcaster
{
public int Port { get; set; }
public byte[] Buffer { get; set; } = StringHelper.GetBytes("Hello World");
private bool _isBroadcasting;
private bool _isListening;
public UdpBasedLanBroadcaster()
{
}
public event Action<EndPoint, string> OnReceive;
public void StartBroadcast()
{
_isBroadcasting = true;
Thread thread = new(Process)
{
IsBackground = true
};
thread.Start();
BIT4Log.Log<ILANBroadcaster>($"开始广播端口{Port}");
}
public void StopBroadcast()
{
_isBroadcasting = false;
BIT4Log.Log<ILANBroadcaster>($"停止广播端口 {Port}");
}
public void StartListen()
{
_isListening = true;
var thread = new Thread(ReceiveThread)
{
IsBackground = true
};
thread.Start();
BIT4Log.Log<ILANBroadcaster>($"开始监听端口:{Port}");
}
public void StopListen()
{
_isListening = false;
BIT4Log.Log<ILANBroadcaster>($"停止监听端口{Port}");
}
private void Process()
{
var udpClient = new UdpClient(new IPEndPoint(IPAddress.Any, 0));
var endpoint = new IPEndPoint(IPAddress.Broadcast, Port);
//其实 IPAddress.Broadcast 就是 255.255.255.255
//下面代码与上面有相同的作用
//IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse("255.255.255.255"), 8080);
try
{
while (_isBroadcasting)
{
udpClient.Send(Buffer, Buffer.Length, endpoint);
Thread.Sleep(1000);
}
}
catch (Exception e)
{
BIT4Log.LogException(e);
}
udpClient.Dispose();
}
private void ReceiveThread()
{
try
{
var udpClient = new UdpClient(new IPEndPoint(IPAddress.Any, Port));
var endpoint = new IPEndPoint(IPAddress.Any, 0);
while (_isListening)
{
var buf = udpClient.Receive(ref endpoint);
var msg = Encoding.Default.GetString(buf);
if (OnReceive is not null)
OnReceive(endpoint, msg);
else
BIT4Log.Log<ILANBroadcaster>($"Receive From {endpoint}:\t{msg}");
Thread.Sleep(500);
}
}
catch (Exception e)
{
BIT4Log.LogException(e);
}
}
}
}