60 네트워크 프로그래밍 맛보기
C#에서 다루는 데이터는 인메모리, 파일, XML과 JSON을 포함하여 여러 데이터를 인터넷과 같은 네트워크를 통해서 주고받을 수 있습니다. 이번 강의는 웹 프로그래밍은 아니지만, 네트워크를 통해서 데이터를 주고받는 간단한 기능을 살펴보겠습니다.
> // System.Net.Http 네임스페이스: 최신 HTTP 응용 프로그램의 프로그래밍 인터페이스를 제공
60.1 HttpClient 클래스로 웹의 데이터를 가져오기
닷넷에서 제공하는 HttpClient 클래스를 사용하면 인터넷에 연결되어 있는 네트워크 상의 데이터를 가져오거나 전송할 수 있습니다. 다음 예제는 닷넷 코어 콘솔 프로젝트에서 http://www.microsoft.com 경로의 HTML 문서를 읽어 콘솔에 출력하는 내용입니다.
코드: HttpClientDemo.cs
// HttpClientDemo/HttpClientDemo.cs
using System;
using System.Net.Http;
using System.Threading.Tasks;
class HttpClientDemo
{
static async Task Main()
{
//[1] HttpClient 개체 생성
HttpClient httpClient = new HttpClient();
//[2] GetAsync() 메서드 호출
HttpResponseMessage httpResponseMessage =
await httpClient.GetAsync("http://www.microsoft.com/");
//[3] HTML 가져오기
string responseBody = await httpResponseMessage.Content.ReadAsStringAsync();
//[4] 출력
Console.WriteLine(responseBody);
}
}
출력 내용은 때에 따라서 다르기에 따로 표현하지 않았습니다. HTML로 다운로드된 문자열은 웹 브라우저와 같은 프로그램에서는 HTML을 실행해서 보여주지만, 이번 예제에서는 그대로 텍스트로 화면에 출력됩니다. GetAsync()와 같이 해당 URL로 데이터를 전송하는 PostAsync()와 같은 메서드도 제공합니다. HttClient 클래스와 같은 API는 때에 따라서 더 향상된 클래스로 추가되어 제공되기도 합니다.
60.1.1 참고: WebClient 클래스로 웹 데이터 읽어오기
이번에는 WebClient 클래스를 사용해보겠습니다. 다음 경로의 URL은 원하는 값으로 변경해서 사용하면 됩니다. 출력 결과물은 따로 표현하지 않겠습니다.
코드: WebClientDemo.cs
// WebClientDemo.cs
using System;
using System.Net;
using System.Threading;
class WebClientDemo
{
static void Main()
{
WebClient client = new WebClient();
// 동기적으로 출력
string google = client.DownloadString("http://www.google.co.kr");
Console.WriteLine("Google: " + google.Substring(0, 10)); // 20자만 가져오기
string naver = client.DownloadString(new Uri("http://www.naver.com"));
Console.WriteLine("Naver: " + naver.Substring(0, 10));
// 비동기적으로 출력
client.DownloadStringAsync(new Uri("http://www.dotnetkorea.com"));
client.DownloadStringCompleted += Client_DownloadStringCompleted;
Thread.Sleep(3000); // 잠시 대기
}
private static void Client_DownloadStringCompleted(object sender,
DownloadStringCompletedEventArgs e)
{
string r = e.Result.Replace("\n", "").Substring(0, 10);
Console.WriteLine($"DotNetKorea: {r}");
}
}
60.1.2 참고: HttpWebRequest 클래스를 사용하여 웹 페이지 가져오기
이번에는 HttpWebRequest 클래스를 사용해 보겠습니다. 다음 경로의 URL은 원하는 값으로 변경해서 사용하면 됩니다. 출력 결과물은 따로 표현하지 않겠습니다.
코드: HttpWebRequestDemo.cs
// HttpWebRequestDemo.cs
using System;
using System.IO;
using System.Net;
class HttpWebRequestDemo
{
static void Main()
{
// 아래 URL에서 HTML문서를 가져올 수 있다고 가정
string url = "http://www.google.com";
var req = HttpWebRequest.CreateHttp(url);
var res = req.GetResponse() as HttpWebResponse;
var stream = res.GetResponseStream();
using (var sr = new StreamReader(stream))
{
var html = sr.ReadToEnd();
Console.WriteLine(html);
}
}
}
60.2 HttpClient 클래스
WebClient 클래스가 레거시 클래스라면 HttpClient 클래스는 최신 버전의 네트워킹 프로그래밍을 위한 클래스입니다.
var client = new WebClient();
var response = await = client.GetAsync("URL");
var content = await = response.Content.ReadAsStringAsync();
60.3 장 요약
닷넷 API 브라우저에서보면 System.Net.Http
네임스페이스를 통해서 많은 수의 API를 제공합니다. 이 역시 모두 다 알 수는 없고, 그럴 필요는 없습니다. C# 콘솔 기반이 아닌 웹과 데스크톱, 모바일 앱 등으로 확장해 나가면 더 쉽게 사용할 수 있는 환경이 됩니다. 네트워크 프로그래밍에 대한 더 자세한 내용은 우선 ASP.NET과 같은 웹 프로그래밍을 먼저 접한 후 Microsoft Learn 등의 네트워크 관련 API를 참고하길 권장합니다. 이번 장도 짧게 마무리 짓도록 하겠습니다.