Skip to content

Commit

Permalink
HttpListener
Browse files Browse the repository at this point in the history
  • Loading branch information
XuanThuLab committed Aug 22, 2020
1 parent a4a4257 commit 8ab58eb
Show file tree
Hide file tree
Showing 5 changed files with 197 additions and 0 deletions.
27 changes: 27 additions & 0 deletions CS029_Networking/7.WebListener/.vscode/launch.json
Original file line number Diff line number Diff line change
@@ -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}"
}
]
}
42 changes: 42 additions & 0 deletions CS029_Networking/7.WebListener/.vscode/tasks.json
Original file line number Diff line number Diff line change
@@ -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"
}
]
}
13 changes: 13 additions & 0 deletions CS029_Networking/7.WebListener/HttpClientExample.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Server.WebListener" Version="1.1.4" />
<PackageReference Include="System.Text.Encoding.CodePages" Version="4.5.1" />
</ItemGroup>

</Project>
107 changes: 107 additions & 0 deletions CS029_Networking/7.WebListener/Program.cs
Original file line number Diff line number Diff line change
@@ -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 = @"<!DOCTYPE html>
<html lang=""en"">
<head><meta charset=""UTF-8"">{0}</head>
<body>{1}</body>
</html>";
string head = "<title>Test WebServer</title>";
var body = new StringBuilder ();
body.Append ("<h1>Request Info</h1>");
body.Append ("<h2>Request Header:</h2>");

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

//Extract request properties
body.Append ("<h2>Request properties:</h2>");
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 ($"<div>{name_pro} : {value_pro}</div>");

};
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");
}

}
}
8 changes: 8 additions & 0 deletions CS029_Networking/7.WebListener/test.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
</body>
</html>

0 comments on commit 8ab58eb

Please sign in to comment.