事例实现一个网页的下载
namespace ConsoleApplication12
{
class Program
{
private const int readBufferSize = 1024;
static void Main(string[] args)
{
if (args.Length != 1)
{
Console.WriteLine("参数错误");
}
string ip = args[0];
//创建任务
Task<String> task = RequestHttpAsync(ip);
//阻塞线程
Console.WriteLine(task.Result);
Console.ReadKey();
}
private static async Task<String> RequestHttpAsync(string ip)
{
using (var client = new TcpClient())
{
try
{
//连接指定的地址 默认端口80
await client.ConnectAsync(ip, 80);
//支持读写
NetworkStream networkStream = client.GetStream();
//请求头
string header = "GET / HTTP/1.1\r\n" + $"Host: {ip}:80\r\n"
+ "Connection: colse\r\n" + "\r\n";
byte[] buffer = Encoding.UTF8.GetBytes(header);
await networkStream.WriteAsync(buffer, 0, buffer.Length);
await networkStream.FlushAsync();
var memoryStream = new MemoryStream();
buffer = new byte[readBufferSize];
int read = 0;
do
{
read = await networkStream.ReadAsync(buffer, 0, readBufferSize);
memoryStream.Write(buffer, 0, read);
Array.Clear(buffer, 0, buffer.Length);
}
while (read > 0);
memoryStream.Seek(0, SeekOrigin.Begin);
var reader = new StreamReader(memoryStream);
return reader.ReadToEnd();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return null;
}
}
}
}
}