Skip to content

Commit

Permalink
新增了http框架,弃掉了ASP.net
Browse files Browse the repository at this point in the history
  • Loading branch information
tianxiu2b2t committed Apr 3, 2024
1 parent c29143c commit e660fc0
Show file tree
Hide file tree
Showing 8 changed files with 208 additions and 28 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -362,4 +362,5 @@ MigrationBackup/
# Fody - auto-generated XML schema
FodyWeavers.xsd

.env.*
.env.*
.lh
12 changes: 12 additions & 0 deletions CSharp-OpenBMCLAPI/Modules/WebServer/Client.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipelines;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.WebUtilities;

namespace CSharpOpenBMCLAPI.Modules.WebServer
{
Expand Down Expand Up @@ -33,5 +35,15 @@ public async Task<byte[]> Read(int n = 1)
Array.Copy(buffer, data, length);
return data;
}
public async Task Write(byte[] data)
{
await this.stream.WriteAsync(data);
await this.stream.FlushAsync();
}
public async Task zeroCopy(Stream stream)
{
await this.stream.CopyToAsync(stream);
await this.stream.FlushAsync();
}
}
}
59 changes: 59 additions & 0 deletions CSharp-OpenBMCLAPI/Modules/WebServer/Header.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpOpenBMCLAPI.Modules.WebServer
{
public class Header
{
Dictionary<string, string> tables;
public Header(Dictionary<string, string> tables) {
this.tables = tables;
}
public Header()
{
this.tables = new Dictionary<string, string>();
}
public static Header fromBytes(byte[][] headers)
{
Dictionary<string, string> tables = new Dictionary<string, string>();
foreach (var header in headers)
{
var h = WebUtils.SplitBytes(header, WebUtils.encode(": ").ToArray(), 1).ToArray();
if (h.Length < 1)
{
continue;
}
tables.TryAdd(WebUtils.decode(h[0]), WebUtils.decode(h[1]));
}
return new Header(tables);
}
public Object get(string key, Object def)
{
return tables.ContainsKey(key) ? tables[key] : def;
}
public void set(string key, Object value)
{
if (value == null)
{
if (tables.ContainsKey(key)) tables.Remove(key);
return;
}
tables.TryAdd(key, value + "");
}
public bool ContainsKey(string key) {
return tables.ContainsKey(key);
}
public string ToString()

Check warning on line 49 in CSharp-OpenBMCLAPI/Modules/WebServer/Header.cs

View workflow job for this annotation

GitHub Actions / build (Release)

'Header.ToString()' hides inherited member 'object.ToString()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.

Check warning on line 49 in CSharp-OpenBMCLAPI/Modules/WebServer/Header.cs

View workflow job for this annotation

GitHub Actions / build (Release)

'Header.ToString()' hides inherited member 'object.ToString()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.
{
string header = "";
foreach (var key in tables.Keys)
{
header += key + ": " + tables[key] + "\r\n";
}
return header;
}
}
}
31 changes: 18 additions & 13 deletions CSharp-OpenBMCLAPI/Modules/WebServer/Request.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,27 @@ namespace CSharpOpenBMCLAPI.Modules.WebServer
{
public class Request
{
string method = "GET";
string path = "/";
string httpProtocol = "HTTP/1.1";
string method;
string path;
string httpProtocol;
Header header;
int bodyLength;
Client client;
byte[] bodyData = new byte[]{};
public Request(Client client, byte[] data) {
byte[][] temp = WebUtils.SplitBytes(data, encode("\r\n\r\n")).ToArray();
byte[][] headers = WebUtils.SplitBytes(temp[0], encode("\r\n")).ToArray();
temp = WebUtils.SplitBytes(headers[0], encode(" "), 2).ToArray();
(method, path, httpProtocol) = (decode(temp[0]), decode(temp[1]), decode(temp[2]));
Console.WriteLine((method, path, httpProtocol));
this.client = client;
byte[][] temp = WebUtils.SplitBytes(data, WebUtils.encode("\r\n\r\n")).ToArray();
this.bodyData = temp[1];
byte[][] requestHeader = WebUtils.SplitBytes(temp[0], WebUtils.encode("\r\n")).ToArray();
temp = WebUtils.SplitBytes(requestHeader[0], WebUtils.encode(" "), 3).ToArray();
(method, path, httpProtocol) = (WebUtils.decode(temp[0]), WebUtils.decode(temp[1]), WebUtils.decode(temp[2]));
Array.Copy(requestHeader, 1, requestHeader, 0, requestHeader.Length - 1);
header = Header.fromBytes(requestHeader);
bodyLength = int.Parse(header.get("Content-Length", 0) + "");
}
public string decode(byte[] data)
public async Task skipContent()
{
return Encoding.UTF8.GetString(data);
}
public byte[] encode(string data) {
return Encoding.UTF8.GetBytes(data).ToArray();
await this.client.Read(bodyLength - bodyData.Length);
}
}
}
81 changes: 81 additions & 0 deletions CSharp-OpenBMCLAPI/Modules/WebServer/Response.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpOpenBMCLAPI.Modules.WebServer
{
public class Response
{
int status_code = 200;
Header header = new Header();
Stream stream = new MemoryStream();
public async Task call(Client client, Request request)
{
header.set("Content-Length", stream.Length);
header.set("Server", "CSharp-SaltWood");
string responseHeader = "HTTP/1.1 " + status_code + " " + GetStatusMsg(status_code) + "\r\n" + header.ToString() + "\r\n";
await client.Write(WebUtils.encode(responseHeader));
}
public static Dictionary<int, string> STATUS_CODES = new Dictionary<int, string>
{
{ 100, "Continue" },
{ 101, "Switching Protocols" },
{ 200, "OK" },
{ 201, "Created" },
{ 202, "Accepted" },
{ 203, "Non-Authoritative Information" },
{ 204, "No Content" },
{ 205, "Reset Content" },
{ 206, "Partial Content" },
{ 300, "Multiple Choices" },
{ 301, "Moved Pemanently" },
{ 302, "Found" },
{ 303, "See Other" },
{ 304, "Not Modified" },
{ 305, "Use Proxy" },
{ 306, "Unused" },
{ 307, "Temporary Redirect" },
{ 400, "Bad Request" },
{ 401, "Unauthorized" },
{ 402, "Payment Required" },
{ 403, "Forbidden" },
{ 404, "Not Found" },
{ 405, "Method Not Allowed" },
{ 406, "Not Acceptable" },
{ 407, "Proxy Authentication Required" },
{ 408, "Request Time-out" },
{ 409, "Conflict" },
{ 410, "Gone" },
{ 411, "Length Required" },
{ 412, "Precondition Failed" },
{ 413, "Request Entity Too Large" },
{ 414, "Request-URI Too Large" },
{ 415, "Unsupported Media Type" },
{ 416, "Requested range not satisfiable" },
{ 417, "Expectation Failed" },
{ 418, "I'm a teapot" },
{ 421, "Misdirected Request" },
{ 422, "Unprocessable Entity" },
{ 423, "Locked" },
{ 424, "Failed Dependency" },
{ 425, "Too Early" },
{ 426, "Upgrade Required" },
{ 428, "Precondition Required" },
{ 429, "Too Many Requests" },
{ 431, "Request Header Fields Too Large" },
{ 451, "Unavailable For Legal Reasons" },
{ 500, "Internal Server Eror" },
{ 501, "Not Implemented" },
{ 502, "Bad Gateway" },
{ 503, "Service Unavailable" },
{ 504, "Gateway Time-out" },
{ 505, "HTTP Version not supported" },
};
public static string GetStatusMsg(int status)
{
return STATUS_CODES.ContainsKey(status) ? STATUS_CODES[status] : STATUS_CODES[int.Parse((status / 100) + "") * 100];
}
}
}
27 changes: 15 additions & 12 deletions CSharp-OpenBMCLAPI/Modules/WebServer/WebServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,31 +35,37 @@ protected async Task<int> AsyncRun()
listener.Start();

HttpListener httpListener = new();
Console.WriteLine("已监听");

while (true)
{
TcpClient tcpClient = await listener.AcceptTcpClientAsync();
Console.WriteLine("Accepted ");
Stream stream = tcpClient.GetStream();
if (_certificate != null)
{
stream = new SslStream(stream, false, ValidateServerCertificate, null);

}
Console.WriteLine("已Handle");
await Handle(new Client(tcpClient, stream));
if (await Handle(new Client(tcpClient, stream)) && tcpClient.Connected)
{
stream.Close();
tcpClient.Close();
}
}
}
protected async Task Handle(Client client)
protected async Task<bool> Handle(Client client) // 返回值代表是否关闭连接?
{
try
{
byte[] buf = await client.Read(this.buffer);
Request request = new Request(client, buf);
// 路由,你需要自己写了
Response response = new Response();
await response.call(client, request); // 可以多次调用Response
return false;
} catch (Exception e)
{
e.PrintTypeInfo();
return true;
}
}

Expand All @@ -76,16 +82,13 @@ public static void printBytes(byte[] bytes)
}
Console.WriteLine(text);
}
public static void printArrayBytes(byte[][] bytes)
{
bytes.ForEach(e => printBytes(e));
}
public static string byteToString(byte hex)
{
return hex <= 8 || (hex >= 11 && hex <= 12) || (hex >= 14 && hex <= 31) || (hex >= 127 && hex <= 255) ? "\\x" + BitConverter.ToString(new byte[] { hex }) : (hex == 9 ? "\\t" : (hex == 10 ? "\\n" : (hex == 13 ? "\\r" : Encoding.ASCII.GetString(new byte[] { hex }))));
}
/*
* By TTB
* function Socket_tostring(hex) {
hex = hex < 0 ? hex + 256 : hex
return hex <= 8 || (hex >= 11 && hex <= 12) || (hex >= 14 && hex <= 31) || (hex >= 127 && hex <= 255) ? "\\x" + format("%02x", hex) : (hex == 9 ? "\\t" : (hex == 10 ? "\\n" : (hex == 13 ? "\\r" : hex.tochar())))
}
*/
}
}
18 changes: 16 additions & 2 deletions CSharp-OpenBMCLAPI/Modules/WebServer/WebUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ namespace CSharpOpenBMCLAPI.Modules.WebServer
{
public static class WebUtils
{
public static List<byte[]> SplitBytes(byte[] data, byte[] key, int count = 0)
public static List<byte[]> SplitBytes(byte[] data, byte[] key, int count = -1)
{
if (count <= -1)
{
Expand Down Expand Up @@ -62,11 +62,25 @@ public static List<byte[]> SplitBytes(byte[] data, byte[] key, int count = 0)
}

// Helper method to create a subarray from an existing array
private static byte[] SubArray(byte[] data, int start, int length)
public static byte[] SubArray(byte[] data, int start, int length)
{
byte[] result = new byte[length];
Array.Copy(data, start, result, 0, length);
return result;
}
public static Object[] SubArray(Object[] data, int start, int length)
{
Object[] result = new Object[length];
Array.Copy(data, start, result, 0, length);
return result;
}
public static string decode(byte[] data)
{
return Encoding.UTF8.GetString(data);
}
public static byte[] encode(string data)
{
return Encoding.UTF8.GetBytes(data).ToArray();
}
}
}
5 changes: 5 additions & 0 deletions CSharp-OpenBMCLAPI/Program.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using CSharpOpenBMCLAPI.Modules;
using CSharpOpenBMCLAPI.Modules.Plugin;
using CSharpOpenBMCLAPI.Modules.Statistician;
using CSharpOpenBMCLAPI.Modules.WebServer;
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;
using System.Reflection;
Expand All @@ -18,6 +19,10 @@ public Program() : base() { }

static void Main(string[] args)
{
WebServer web = new WebServer(8800, null);
web.Start();
web.WaitForStop();
//
SharedData.Logger.LogSystem($"Starting CSharp-OpenBMCLAPI v{SharedData.Config.clusterVersion}");
SharedData.Logger.LogSystem("高性能、低メモリ占有!");
SharedData.Logger.LogSystem($"运行时环境:{Utils.GetRuntime()}");
Expand Down

0 comments on commit e660fc0

Please sign in to comment.