Skip to content

Commit

Permalink
TpcClient downlad Url
Browse files Browse the repository at this point in the history
  • Loading branch information
XuanThuLab committed Aug 22, 2020
1 parent a4a4257 commit 21c24ae
Show file tree
Hide file tree
Showing 4 changed files with 198 additions and 0 deletions.
27 changes: 27 additions & 0 deletions CS029_Networking/8.TcpClient/.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/netcoreapp2.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/8.TcpClient/.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/8.TcpClient/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>netcoreapp2.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>
116 changes: 116 additions & 0 deletions CS029_Networking/8.TcpClient/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Text;
using System.Net.Sockets;
using System.Net.Http;
using System.IO;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

namespace TCP
{

class Program
{
// Phương thức này gọi bởi RemoteCertificateValidationDelegate trong quá trình xác thức SSL
// chỉ dùng khi kết nối HTTPS

public static bool ValidateServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
Console.WriteLine("ValidateServerCertificate");
if (sslPolicyErrors == SslPolicyErrors.None) return true;
Console.WriteLine("Certificate error: {0}", sslPolicyErrors);

// Do not allow this client to communicate with unauthenticated servers.
return false;
}

// Kết nối đến server Tpc bằng TcpClient, đọc nội dung trả về
public static async Task ReadHtmlAsync(string url) {

using (var client = new TcpClient())
{
Console.WriteLine($"Start get {url}");
Uri uri = new Uri(url);

var hostAdress = await Dns.GetHostAddressesAsync(uri.Host);
IPAddress ipaddrress = hostAdress[0];
Console.WriteLine($"Host: {uri.Host}, IP: {ipaddrress}:{uri.Port}");
await client.ConnectAsync(ipaddrress.MapToIPv4(), uri.Port);
Console.WriteLine("Connected");
Console.WriteLine();


Stream stream;
if (uri.Scheme == "https")
{
// SslStream
stream = new SslStream(client.GetStream(),false,
new RemoteCertificateValidationCallback (ValidateServerCertificate),
null);
(stream as SslStream).AuthenticateAsClient(uri.Host);
}
else {
// NetworkStream
stream = client.GetStream();
}

Console.WriteLine($"Get Stream OK: {stream.GetType().Name}");


// Xem: /psr-7-chuan-giao-dien-thong-diep-http.html#HTTPRequest
StringBuilder header = new StringBuilder();
header.Append($"GET {uri.PathAndQuery} HTTP/1.1\r\n");
// header.Append($"GET {uri.PathAndQuery} HTTP/2\r\n");
header.Append($"Host: {uri.Host}\r\n");
header.Append($"\r\n");

Console.WriteLine("Request:");
Console.WriteLine(header);

byte[] bsend = Encoding.UTF8.GetBytes(header.ToString());
await stream.WriteAsync(bsend, 0, bsend.Length);

await stream.FlushAsync();

Console.WriteLine("Send Message OK");


var ms = new MemoryStream();
byte [] buffer = new byte[255];
int bytes = -1;
do
{
bytes = await stream.ReadAsync(buffer, 0, buffer.Length);

// Lưu dữ liệu tải về vào ms
ms.Write(buffer, 0, bytes);

Array.Clear(buffer, 0, buffer.Length);

} while (bytes != 0);

Console.WriteLine($"Read OK");

ms.Seek(0, SeekOrigin.Begin);
var reader = new StreamReader(ms);
string html = reader.ReadToEnd();
Console.WriteLine("Response:");
Console.WriteLine(html);

}
}
static async Task Main(string[] args)
{
string url = "https://google.com.vn";
await ReadHtmlAsync(url);
}

}
}

0 comments on commit 21c24ae

Please sign in to comment.