■ 대용량 데이터를 스트리밍 방식으로 전달받는 방법을 보여준다.
[TestLibrary 프로젝트]
▶ ValueModel.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
namespace TestLibrary { /// <summary> /// 값 모델 /// </summary> public class ValueModel { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region ID - ID /// <summary> /// ID /// </summary> public int ID { get; set; } #endregion #region 데이터 - Data /// <summary> /// 데이터 /// </summary> public string Data { get; set; } #endregion #region 태그 - Tag /// <summary> /// 태그 /// </summary> public string Tag { get; set; } #endregion } } |
[TestClient 프로젝트]
▶ Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 |
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using Newtonsoft.Json; using TestLibrary; namespace TestClient { /// <summary> /// 프로그램 /// </summary> class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 프로그램 시작하기 - Main() /// <summary> /// 프로그램 시작하기 /// </summary> private static void Main() { Console.Title = "대용량 데이터를 스트리밍 방식으로 전달받기"; Console.WriteLine("PRESS ANY KEY TO CONTINUE..."); Console.ReadKey(true); //TestPOSTData1(); //TestPOSTData2(); TestGETData(); Console.WriteLine("PRESS ANY KEY TO EXIT..."); Console.ReadKey(true); } #endregion #region POST 데이터 구하기 1 - GetPOSTData1<TResultItem>(url, source) /// <summary> /// POST 데이터 구하기 1 /// </summary> /// <typeparam name="TResultItem">결과 항목 타입</typeparam> /// <param name="url">URL</param> /// <param name="source">소스 객체</param> /// <returns>결과 항목 타입 열거 가능형</returns> private static IEnumerable<TResultItem> GetPOSTData1<TResultItem>(string url, object source) { string sourceJSON = JsonConvert.SerializeObject(source); HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, url); requestMessage.Content = new StringContent(sourceJSON, Encoding.UTF8, "application/json"); requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpClient client = new HttpClient(); HttpResponseMessage responseMessage = client.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead).Result; responseMessage.EnsureSuccessStatusCode(); using(Stream stream = responseMessage.Content.ReadAsStreamAsync().Result) { using(StreamReader streamReader = new StreamReader(stream)) { JsonSerializer serializer = new JsonSerializer(); using(JsonTextReader jsonTextReader = new JsonTextReader(streamReader)) { while(jsonTextReader.Read()) { if(jsonTextReader.TokenType != JsonToken.StartArray && jsonTextReader.TokenType != JsonToken.EndArray) { yield return serializer.Deserialize<TResultItem>(jsonTextReader); } } } } } } #endregion #region POST 데이터 테스트하기 1 - TestPOSTData1() /// <summary> /// POST 데이터 테스트하기 1 /// </summary> private static void TestPOSTData1() { string url = "http://localhost:5569/api/test/postdata"; ValueModel source = new ValueModel(); source.ID = -1; source.Data = "NODATA"; source.Tag = "POST3"; foreach(ValueModel value in GetPOSTData1<ValueModel>(url, source)) { Console.WriteLine("{0} {1} {2}", value.ID, value.Data.Length, value.Tag); } } #endregion #region POST 스트림 구하기 - POSTGetStream(serverURL, contentType, encoding, argument, timeOut) /// <summary> /// POST 스트림 구하기 /// </summary> /// <param name="serverURL">서버 URL</param> /// <param name="contentType">컨텐츠 타입</param> /// <param name="encoding">인코딩</param> /// <param name="argument">인자 문자열</param> /// <param name="timeOut">타임 아웃</param> /// <returns>POST 스트림</returns> private static Stream POSTGetStream(string serverURL, string contentType, Encoding encoding, string argument, int? timeOut = null) { byte[] argumentArray = encoding.GetBytes(argument); HttpWebRequest request = WebRequest.Create(serverURL) as HttpWebRequest; request.ProtocolVersion = HttpVersion.Version11; request.AllowAutoRedirect = true; request.AllowWriteStreamBuffering = true; request.Method = WebRequestMethods.Http.Post; request.ContentType = contentType; request.ContentLength = argumentArray.Length; if(timeOut.HasValue) { request.Timeout = timeOut.Value; } using(Stream requestStream = request.GetRequestStream()) { requestStream.Write(argumentArray, 0, argumentArray.Length); } HttpWebResponse response = request.GetResponse() as HttpWebResponse; Stream responseStream = response.GetResponseStream(); return responseStream; } #endregion #region POST 데이터 구하기 2 - GetPOSTData2<TResultItem>(url, source) /// <summary> /// POST 데이터 구하기 2 /// </summary> /// <typeparam name="TResultItem">결과 항목 타입</typeparam> /// <param name="url">URL</param> /// <param name="source">소스 객체</param> /// <returns>결과 항목 타입 열거 가능형</returns> private static IEnumerable<TResultItem> GetPOSTData2<TResultItem>(string url, object source) { string sourceJSON = JsonConvert.SerializeObject(source); using(Stream stream = POSTGetStream(url, "application/json; charset=utf-8", Encoding.UTF8, sourceJSON)) { using(StreamReader streamReader = new StreamReader(stream)) { using(JsonTextReader jsonTextReader = new JsonTextReader(streamReader)) { JsonSerializer serializer = new JsonSerializer(); while(jsonTextReader.Read()) { if(jsonTextReader.TokenType != JsonToken.StartArray && jsonTextReader.TokenType != JsonToken.EndArray) { yield return serializer.Deserialize<TResultItem>(jsonTextReader); } } } } } } #endregion #region POST 데이터 테스트하기 2 - TestPOSTData2() /// <summary> /// POST 데이터 테스트하기 2 /// </summary> private static void TestPOSTData2() { string url = "http://localhost:5569/api/test/postdata"; ValueModel source = new ValueModel(); source.ID = -1; source.Data = "NODATA"; source.Tag = "POST3"; foreach(ValueModel value in GetPOSTData2<ValueModel>(url, source)) { Console.WriteLine("{0} {1} {2}", value.ID, value.Data.Length, value.Tag); } } #endregion #region GET 데이터 구하기 - GetGETData<TResultItem>(url) /// <summary> /// GET 데이터 구하기 /// </summary> /// <typeparam name="TResultItem">결과 항목 타입</typeparam> /// <param name="url">URL</param> /// <returns>결과 항목 열거 가능형</returns> private static IEnumerable<TResultItem> GetGETData<TResultItem>(string url) { HttpClient client = new HttpClient(); MediaTypeWithQualityHeaderValue headerValue = new MediaTypeWithQualityHeaderValue("application/json"); client.DefaultRequestHeaders.Accept.Add(headerValue); using(Stream stream = client.GetStreamAsync(url).Result) { using(StreamReader streamReader = new StreamReader(stream)) { JsonSerializer serializer = new JsonSerializer(); using(JsonTextReader jsonTextReader = new JsonTextReader(streamReader)) { while(jsonTextReader.Read()) { if(jsonTextReader.TokenType != JsonToken.StartArray && jsonTextReader.TokenType != JsonToken.EndArray) { yield return serializer.Deserialize<TResultItem>(jsonTextReader); } } } } } } #endregion #region GET 데이터 테스트하기 - TestGETData() /// <summary> /// GET 데이터 테스트하기 /// </summary> private static void TestGETData() { string url = "http://localhost:5569/api/test/getdata?tag=GET"; foreach(ValueModel value in GetGETData<ValueModel>(url)) { Console.WriteLine("{0} {1} {2}", value.ID, value.Data.Length, value.Tag); } } #endregion } } |
[TestServer 프로젝트]
▶ Controllers/TestController.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 |
using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using System.Linq; using System.Text; using TestLibrary; namespace TestServer.Controllers { /// <summary> /// 테스트 컨트롤러 /// </summary> [Route("api/[controller]")] public class TestController : Controller { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 샘플 데이터 /// </summary> private static string _sampleData; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Static #region 생성자 - TestController() /// <summary> /// 생성자 /// </summary> static TestController() { StringBuilder stringBuilder = new StringBuilder(); for(int i = 0; i < 100; i++) { stringBuilder.Append("ABCDEFGHIJABCDEFGHIJ"); stringBuilder.Append("ABCDEFGHIJABCDEFGHIJ"); stringBuilder.Append("ABCDEFGHIJABCDEFGHIJ"); stringBuilder.Append("ABCDEFGHIJABCDEFGHIJ"); stringBuilder.Append("ABCDEFGHIJABCDEFGHIJ"); } _sampleData = stringBuilder.ToString(); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region GET 데이터 구하기 - GetData(tag) /// <summary> /// GET 데이터 구하기 /// </summary> /// <param name="tag">태그</param> /// <returns>값 열거 가능형</returns> [HttpGet] [Route("GetData")] public IEnumerable<ValueModel> GetData(string tag) { foreach(int i in Enumerable.Range(1, 1000000)) { yield return new ValueModel() { ID = i, Data = _sampleData, Tag = tag }; } } #endregion #region POST 데이터 구하기 - PostData(source) /// <summary> /// POST 데이터 구하기 /// </summary> /// <param name="source">소스 값</param> /// <returns>값 열거 가능형</returns> [HttpPost] [Route("PostData")] public IEnumerable<ValueModel> PostData([FromBody] ValueModel source) { foreach(int i in Enumerable.Range(1, 1000000)) { yield return new ValueModel() { ID = i, Data = _sampleData, Tag = source.Tag }; } } #endregion } } |