-
Notifications
You must be signed in to change notification settings - Fork 85
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
ReadAsStreamAsync và ReadAsByteArrayAsync
- Loading branch information
XuanThuLab
committed
Aug 21, 2020
1 parent
a4a4257
commit 081bc86
Showing
4 changed files
with
185 additions
and
0 deletions.
There are no files selected for viewing
27 changes: 27 additions & 0 deletions
27
CS029_Networking/2.HttpClientExampleRead/.vscode/launch.json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
42
CS029_Networking/2.HttpClientExampleRead/.vscode/tasks.json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | ||
} | ||
] | ||
} |
8 changes: 8 additions & 0 deletions
8
CS029_Networking/2.HttpClientExampleRead/HttpClientExample.csproj
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
|
||
<PropertyGroup> | ||
<OutputType>Exe</OutputType> | ||
<TargetFramework>netcoreapp2.1</TargetFramework> | ||
</PropertyGroup> | ||
|
||
</Project> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,108 @@ | ||
using System; | ||
using System.IO; | ||
using System.Linq; | ||
using System.Net; | ||
using System.Net.Http; | ||
using System.Net.Http.Headers; | ||
using System.Threading; | ||
using System.Threading.Tasks; | ||
|
||
namespace HttpClientExample { | ||
public class ViduHttpClient : IDisposable { | ||
|
||
public HttpClient httpClient; | ||
public ViduHttpClient () { | ||
httpClient = new HttpClient (); | ||
// Thiết lập httpClient nếu muốn ở đây | ||
} | ||
|
||
// Giải phóng tài nguyên | ||
public void Dispose () { | ||
if (httpClient != null) { | ||
httpClient.Dispose (); | ||
httpClient = null; | ||
} | ||
} | ||
|
||
// Tải từ url trả về mảng byte dữ liệu | ||
public async Task<byte[]> DownloadDataBytes (string url) { | ||
Console.WriteLine ($"Starting connect {url}"); | ||
try { | ||
HttpResponseMessage response = await httpClient.GetAsync (url); | ||
response.EnsureSuccessStatusCode (); | ||
var data = await response.Content.ReadAsByteArrayAsync(); | ||
Console.WriteLine("Received data success"); | ||
return data; | ||
} catch (Exception e) { | ||
Console.WriteLine (e.Message); | ||
throw e; | ||
} | ||
} | ||
|
||
// Tải từ url, trả về stream để đọc dữ liệu (xem bài về stream) | ||
public async Task<Stream> DownloadDataStream (string url) { | ||
Console.WriteLine ($"Starting connect {url}"); | ||
try { | ||
HttpResponseMessage response = await httpClient.GetAsync (url); | ||
response.EnsureSuccessStatusCode (); | ||
var stream = await response.Content.ReadAsStreamAsync(); | ||
Console.WriteLine("Stream for read data OK"); | ||
return stream; | ||
|
||
} catch (Exception e) { | ||
Console.WriteLine (e.Message); | ||
throw e; | ||
} | ||
} | ||
} | ||
|
||
class Program { | ||
|
||
static async Task Main (string[] args) { | ||
|
||
var httpclient = new ViduHttpClient (); | ||
|
||
// Tải dữ liệu - trả về mảng byte[] | ||
var url1 = "https://raw.githubusercontent.com/xuanthulabnet/jekyll-example/master/images/jekyll-01.png"; | ||
var task1 = httpclient.DownloadDataBytes(url1); | ||
|
||
|
||
//Tải dữ liệu - trả về stream | ||
string url2 = "https://raw.githubusercontent.com/xuanthulabnet/linux-centos/master/docs/samba1.png"; | ||
var task2 = httpclient.DownloadDataStream (url2); | ||
|
||
|
||
|
||
|
||
await task1; // chờ cho tải xong | ||
byte[] dataimg = task1.Result; | ||
// Lưu mảng ra file anh1.png | ||
string filepath = "anh1.png"; | ||
using (var stream = new FileStream (filepath, FileMode.Create, FileAccess.Write, FileShare.None)) { | ||
stream.Write (dataimg, 0, dataimg.Length); | ||
Console.WriteLine("save " + filepath); | ||
} | ||
|
||
|
||
await task2; // chờ cho tải xong | ||
int SIZEBUFFER = 500; | ||
// Đọc dữ liệu từ stream trả về, lưu ra file anh2.pnng | ||
string filepath2 = "anh2.png"; | ||
using (var streamwrite = File.OpenWrite (filepath2)) | ||
using (var streamread = task2.Result) { | ||
byte[] buffer = new byte[SIZEBUFFER]; // tạo bộ nhớ đệm lưu dữ liệu khi đọc stream | ||
bool endread = false; | ||
do { | ||
int numberRead = streamread.Read (buffer, 0, SIZEBUFFER); | ||
if (numberRead == 0) endread = true; | ||
else { | ||
streamwrite.Write (buffer, 0, numberRead); | ||
} | ||
|
||
} while (!endread); | ||
|
||
} | ||
Console.WriteLine("save " + filepath2); | ||
} | ||
} | ||
} |