diff --git a/CS029_Networking/7.WebListener/.vscode/launch.json b/CS029_Networking/7.WebListener/.vscode/launch.json new file mode 100644 index 0000000..7970ee4 --- /dev/null +++ b/CS029_Networking/7.WebListener/.vscode/launch.json @@ -0,0 +1,27 @@ +{ + // Use IntelliSense to find out which attributes exist for C# debugging + // Use hover for the description of the existing attributes + // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md + "version": "0.2.0", + "configurations": [ + { + "name": ".NET Core Launch (console)", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build", + // If you have changed target frameworks, make sure to update the program path. + "program": "${workspaceFolder}/bin/Debug/netcoreapp3.1/HttpClientExample.dll", + "args": [], + "cwd": "${workspaceFolder}", + // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console + "console": "internalConsole", + "stopAtEntry": false + }, + { + "name": ".NET Core Attach", + "type": "coreclr", + "request": "attach", + "processId": "${command:pickProcess}" + } + ] +} \ No newline at end of file diff --git a/CS029_Networking/7.WebListener/.vscode/tasks.json b/CS029_Networking/7.WebListener/.vscode/tasks.json new file mode 100644 index 0000000..0ee9d18 --- /dev/null +++ b/CS029_Networking/7.WebListener/.vscode/tasks.json @@ -0,0 +1,42 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "label": "build", + "command": "dotnet", + "type": "process", + "args": [ + "build", + "${workspaceFolder}/HttpClientExample.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "publish", + "command": "dotnet", + "type": "process", + "args": [ + "publish", + "${workspaceFolder}/HttpClientExample.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "watch", + "command": "dotnet", + "type": "process", + "args": [ + "watch", + "run", + "${workspaceFolder}/HttpClientExample.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + } + ] +} \ No newline at end of file diff --git a/CS029_Networking/7.WebListener/HttpClientExample.csproj b/CS029_Networking/7.WebListener/HttpClientExample.csproj new file mode 100755 index 0000000..f567995 --- /dev/null +++ b/CS029_Networking/7.WebListener/HttpClientExample.csproj @@ -0,0 +1,13 @@ + + + + Exe + netcoreapp3.1 + + + + + + + + diff --git a/CS029_Networking/7.WebListener/Program.cs b/CS029_Networking/7.WebListener/Program.cs new file mode 100755 index 0000000..2abddbe --- /dev/null +++ b/CS029_Networking/7.WebListener/Program.cs @@ -0,0 +1,107 @@ +using System; +using System.Linq; +using System.Net; +using System.Text; +using System.Threading.Tasks; + +namespace HttpListenerExample { + + class Program { + + + // Chạy một HTTP Server, prefixes example: new string[] { "http://*:8080/" } + public static async Task RunWebserverAsync (params string[] prefixes) { + + if (!HttpListener.IsSupported) + throw new Exception ("Máy không hỗ trợ HttpListener."); + + if (prefixes == null || prefixes.Length == 0) + throw new ArgumentException ("prefixes"); + + // Khởi tạo HttpListener + HttpListener listener = new HttpListener (); + + foreach (string s in prefixes) { + listener.Prefixes.Add (s); + } + Console.WriteLine ("Server start ..."); + // Http bắt đầu lắng nghe truy vấn gửi đến + listener.Start(); + + do { + + + HttpListenerContext context = await listener.GetContextAsync(); + HttpListenerRequest request = context.Request; + HttpListenerResponse response = context.Response; + + // Refuse connect + if (response.StatusCode != 200) + { + Console.WriteLine($"{request.HttpMethod} {request.RawUrl} LỖI {response.StatusCode}"); + continue; + } + + + Console.WriteLine($"{request.HttpMethod} {request.RawUrl} from IP {context.Request.RemoteEndPoint.ToString()}"); + + + // Gửi thông tin về cho Client + context.Response.Headers.Add ("content-type", "text/html"); + context.Response.StatusCode = (int) HttpStatusCode.OK; + byte[] buffer = GenerateHTMP(context.Request); + response.ContentLength64 = buffer.Length; + System.IO.Stream output = response.OutputStream; + await output.WriteAsync (buffer, 0, buffer.Length); + + + } while (listener.IsListening); + + + // listener.Stop(); + + } + + // Tạo nội dung HTML trả về cho Client (HTML chứa thông tin về Request) + public static byte[] GenerateHTMP (HttpListenerRequest request) { + string format = @" + + {0} + {1} + "; + string head = "Test WebServer"; + var body = new StringBuilder (); + body.Append ("

Request Info

"); + body.Append ("

Request Header:

"); + + // Header infomation + var headers = from key in request.Headers.AllKeys + select $"
{key} : {string.Join(",", request.Headers.GetValues(key))}
"; + body.Append (string.Join ("", headers)); + + //Extract request properties + body.Append ("

Request properties:

"); + var properties = request.GetType ().GetProperties (); + foreach (var property in properties) { + var name_pro = property.Name; + string value_pro; + try { + value_pro = property.GetValue (request).ToString (); + } catch (Exception e) { + value_pro = e.Message; + } + body.Append ($"
{name_pro} : {value_pro}
"); + + }; + string html = string.Format (format, head, body.ToString ()); + return Encoding.UTF8.GetBytes(html); + } + + static async Task Main (string[] args) { + await RunWebserverAsync (new string[] { "http://*:8080/" }); + Console.ReadKey(); + Console.WriteLine("End"); + } + + } +} \ No newline at end of file diff --git a/CS029_Networking/7.WebListener/test.html b/CS029_Networking/7.WebListener/test.html new file mode 100755 index 0000000..716852b --- /dev/null +++ b/CS029_Networking/7.WebListener/test.html @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file