■ HttpListener 클래스를 사용해 웹 서버를 만드는 방법을 보여준다.
▶ MainForm.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 |
using System; using System.Windows.Forms; namespace TestProject { /// <summary> /// 메인 폼 /// </summary> public partial class MainForm : Form { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 서버 /// </summary> private WebServer server = null; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainForm() /// <summary> /// 생성자 /// </summary> public MainForm() { InitializeComponent(); this.server = new WebServer(); this.server.AddBindingAddress("http://localhost:9999/"); // 포트 번호까지 반드시 설정합니다. this.server.RootPath = "c:\\wwwroot"; this.server.ActionRequested += server_ActionRequested; FormClosing += Form_FormClosing; this.startButton.Click += startButton_Click; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private #region 폼을 닫을려는 경우 처리하기 - Form_FormClosing(sender, e) /// <summary> /// 폼을 닫을려는 경우 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void Form_FormClosing(object sender, FormClosingEventArgs e) { if(this.server.IsRunning) { this.server.Stop(); this.server = null; } } #endregion #region Start 버튼 클릭시 처리하기 - startButton_Click(sender, e) /// <summary> /// Start 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void startButton_Click(object sender, EventArgs e) { if(this.server.IsRunning) { this.server.Stop(); this.startButton.Text = "Start"; } else { this.server.Start(); this.startButton.Text = "Stop"; } } #endregion #region 서버 액션 요청시 처리하기 - server_ActionRequested(sender, e) /// <summary> /// 서버 액션 요청시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void server_ActionRequested(object sender, ActionRequestedEventArgs e) { e.Server.WriteDefaultAction(e.Context); } #endregion } } |
▶ WebServer.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 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 |
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Text; using System.Threading; namespace TestProject { /// <summary> /// 웹 서버 /// </summary> public class WebServer : IDisposable { //////////////////////////////////////////////////////////////////////////////////////////////////// Event ////////////////////////////////////////////////////////////////////////////////////////// Public #region 액션 요청시 이벤트 - ActionRequested /// <summary> /// 액션 요청시 이벤트 /// </summary> public event EventHandler<ActionRequestedEventArgs> ActionRequested; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// MIME 타입 딕셔너리 /// </summary> private static Dictionary<string, string> _mimeTypeDictionary = null; #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 청취자 /// </summary> private HttpListener listener = null; /// <summary> /// 바인딩 주소 리스트 /// </summary> private List<string> bindingAddressList = new List<string>(); /// <summary> /// 루트 경로 /// </summary> private string rootPath = null; /// <summary> /// 청취 스레드 /// </summary> private Thread listenThread = null; /// <summary> /// 응답 스레드 리스트 /// </summary> private List<Thread> responseThreadList = null; /// <summary> /// 실행 여부 /// </summary> private bool isRunning = false; /// <summary> /// 해제 여부 /// </summary> private bool isDisposed = false; /// <summary> /// 버퍼 크기 /// </summary> private const int BUFFER_SIZE = 4096; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 루트 경로 - RootPath /// <summary> /// 루트 경로 /// </summary> public string RootPath { get { return this.rootPath; } set { if(this.isRunning) { return; } this.rootPath = value; } } #endregion #region 실행 여부 - IsRunning /// <summary> /// 실행 여부 /// </summary> public bool IsRunning { get { return this.isRunning; } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Static #region 생성자 - WebServer() /// <summary> /// 생성자 /// </summary> static WebServer() { _mimeTypeDictionary = new Dictionary<string, string>(); _mimeTypeDictionary.Add(".js" , "application/js" ); _mimeTypeDictionary.Add(".json", "application/json" ); _mimeTypeDictionary.Add(".html", "text/html; charset=utf-8"); _mimeTypeDictionary.Add(".css" , "text/css; charset=utf-8" ); _mimeTypeDictionary.Add(".text", "text/text; charset=utf-8"); _mimeTypeDictionary.Add(".jpg" , "image/jpeg" ); _mimeTypeDictionary.Add(".png" , "image/png" ); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - WebServer() /// <summary> /// 생성자 /// </summary> public WebServer() { } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 바인딩 주소 포함 여부 구하기 - ContainsBindingAddress(bindingAddress) /// <summary> /// 바인딩 주소 포함 여부 구하기 /// </summary> /// <param name="bindingAddress">바인딩 주소</param> /// <returns>바인딩 주소 포함 여부</returns> public bool ContainsBindingAddress(string bindingAddress) { return this.bindingAddressList.Contains(bindingAddress); } #endregion #region 바인딩 주소 추가하기 - AddBindingAddress(bindingAddress) /// <summary> /// 바인딩 주소 추가하기 /// </summary> /// <param name="bindingAddress"></param> public void AddBindingAddress(string bindingAddress) { if(this.isRunning) { return; } if(ContainsBindingAddress(bindingAddress)) { return; } this.bindingAddressList.Add(bindingAddress); } #endregion #region 바인딩 주소 제거하기 - RemoveBindingAddress(bindingAddress) /// <summary> /// 바인딩 주소 제거하기 /// </summary> /// <param name="bindingAddress">바인딩 주소</param> public void RemoveBindingAddress(string bindingAddress) { if(this.isRunning) { return; } if(!ContainsBindingAddress(bindingAddress)) { return; } this.bindingAddressList.Remove(bindingAddress); } #endregion #region 바인딩 주소 리스트 지우기 - ClearBindingAddressList() /// <summary> /// 바인딩 주소 리스트 지우기 /// </summary> public void ClearBindingAddressList() { if(this.isRunning) { return; } this.bindingAddressList.Clear(); } #endregion #region 시작하기 - Start() /// <summary> /// 시작하기 /// </summary> public void Start() { if(this.isRunning) { return; } if(this.bindingAddressList == null || this.bindingAddressList.Count == 0) { return; } this.listener = new HttpListener(); foreach(string bindingAddress in this.bindingAddressList) { this.listener.Prefixes.Add(bindingAddress); } this.listener.AuthenticationSchemes = AuthenticationSchemes.Basic | AuthenticationSchemes.Anonymous; this.listener.Start(); this.isRunning = true; if(this.responseThreadList != null) { foreach(Thread responseThread in this.responseThreadList) { responseThread.Abort(); } this.responseThreadList.Clear(); } this.responseThreadList = new List<Thread>(); this.listenThread = new Thread(new ThreadStart(Listen)); this.listenThread.IsBackground = true; this.listenThread.Start(); } #endregion #region 중단하기 - Stop() /// <summary> /// 중단하기 /// </summary> public void Stop() { this.isRunning = false; if(this.listenThread != null) { this.listenThread.Abort(); this.listenThread = null; } if(this.responseThreadList != null) { foreach(Thread responseThread in this.responseThreadList) { responseThread.Abort(); } this.responseThreadList.Clear(); } if(this.listener != null) { this.listener.Stop(); this.listener.Close(); this.listener = null; } } #endregion #region POST 데이터 구하기 - GetPOSTData(request) /// <summary> /// POST 데이터 구하기 /// </summary> /// <param name="request">요청</param> /// <returns>POST 데이터</returns> public string GetPOSTData(HttpListenerRequest request) { if(!request.HasEntityBody) { return null; } using(StreamReader reader = new StreamReader(request.InputStream, request.ContentEncoding)) { return reader.ReadToEnd(); } } #endregion #region 쿼리 문자열 구하기 - GetQueryString(request) /// <summary> /// 쿼리 문자열 구하기 /// </summary> /// <param name="request">요청</param> /// <returns>쿼리 문자열</returns> public string GetQueryString(HttpListenerRequest request) { if(request.QueryString == null || request.QueryString.Count == 0) { return null; } StringBuilder stringBuilder = new StringBuilder(); foreach(string key in request.QueryString.AllKeys) { stringBuilder.Append("&"); stringBuilder.AppendFormat("{0}={1}", key, request.QueryString[key]); } return stringBuilder.ToString().TrimStart('&'); } #endregion #region 파일 쓰기 - WriteFile(request, filePath) /// <summary> /// 파일 쓰기 /// </summary> /// <param name="response">응답</param> /// <param name="filePath">파일 경로</param> public void WriteFile(HttpListenerResponse response, string filePath) { string mimeType = GetMIMEType(filePath); response.Headers.Add(HttpResponseHeader.ContentType, mimeType); using(BinaryReader reader = new BinaryReader(new FileStream(filePath, FileMode.Open, FileAccess.Read))) { byte[] byteArray = new byte[BUFFER_SIZE]; int readCount; while((readCount = reader.Read(byteArray, 0, byteArray.Length)) > 0) { response.OutputStream.Write(byteArray, 0, readCount); } } } #endregion #region 쓰기 - Write(response, message, addHeader) /// <summary> /// 쓰기 /// </summary> /// <param name="response">응답</param> /// <param name="message">메시지</param> /// <param name="addHeader">헤더 추가 여부</param> public void Write(HttpListenerResponse response, string message, bool addHeader = false) { if(addHeader) { response.Headers.Add(HttpResponseHeader.ContentType, "text/html; charset=utf-8"); } byte[] byteArray = Encoding.UTF8.GetBytes(message); response.OutputStream.Write(byteArray, 0, byteArray.Length); } #endregion #region 디폴트 액션 쓰기 - WriteDefaultAction(context) /// <summary> /// 디폴트 액션 쓰기 /// </summary> /// <param name="context">컨텍스트</param> public void WriteDefaultAction(HttpListenerContext context) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendFormat("요청 일시 : {0}", DateTime.Now); stringBuilder.AppendLine("<br>"); stringBuilder.AppendFormat("요청 URL : {0}", context.Request.Url); stringBuilder.AppendLine("<br>"); stringBuilder.AppendFormat("액션명 : {0}", context.Request.RawUrl.Substring(0, context.Request.RawUrl.IndexOf("?"))); stringBuilder.AppendLine("<br>"); stringBuilder.AppendFormat("요청 종류 : {0}", context.Request.HttpMethod); stringBuilder.AppendLine("<br>"); stringBuilder.AppendFormat("POST DATA : {0}", GetPOSTData(context.Request)); stringBuilder.AppendLine("<br>"); stringBuilder.AppendFormat("QUERY STRING : {0}", GetQueryString(context.Request)); stringBuilder.AppendLine("<br>"); Write(context.Response, stringBuilder.ToString(), true); } #endregion #region 리소스 해제하기 - Dispose() /// <summary> /// 리소스 해제하기 /// </summary> public void Dispose() { Dispose(true); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 리소스 해제하기 - Dispose(disposing) /// <summary> /// 리소스 해제하기 /// </summary> /// <param name="disposing">해제 여부</param> protected virtual void Dispose(bool disposing) { if(!this.isDisposed) { if(disposing) { Stop(); } this.isDisposed = true; } } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region 물리적 경로 구하기 - GetPhysicalPath(logicalPath) /// <summary> /// 물리적 경로 구하기 /// </summary> /// <param name="logicalPath">논리적 경로</param> /// <returns>물리적 경로</returns> private string GetPhysicalPath(string logicalPath) { string physicalPath = logicalPath.Replace('/', Path.DirectorySeparatorChar).TrimStart(Path.DirectorySeparatorChar); return physicalPath; } #endregion #region MIME 타입 구하기 - GetMIMEType(filePath) /// <summary> /// MIME 타입 구하기 /// </summary> /// <param name="filePath">파일 경로</param> /// <returns>MIME 타입</returns> private string GetMIMEType(string filePath) { string fileExtension = Path.GetExtension(filePath); if(_mimeTypeDictionary.ContainsKey(fileExtension)) { return _mimeTypeDictionary[fileExtension]; } else { return "application/octet-stream"; } } #endregion #region 디폴트 요청 여부 구하기 - IsDefaultRequest(request) /// <summary> /// 디폴트 요청 여부 구하기 /// </summary> /// <param name="request">요청</param> /// <returns>디폴트 요청 여부</returns> private bool IsDefaultRequest(HttpListenerRequest request) { bool isDefaultRequest = (request.Url.AbsolutePath == string.Empty || request.Url.AbsolutePath == "/"); return isDefaultRequest; } #endregion #region 파일 요청 여부 구하기 - IsFileRequest(request) /// <summary> /// 파일 요청 여부 구하기 /// </summary> /// <param name="request">요청</param> /// <returns>파일 요청 여부</returns> private bool IsFileRequest(HttpListenerRequest request) { string fileExtension = Path.GetExtension(request.Url.AbsolutePath); bool isFileRequest = _mimeTypeDictionary.ContainsKey(fileExtension); return isFileRequest; } #endregion #region 액션 요청 여부 구하기 - IsActionRequest(request) /// <summary> /// 액션 요청 여부 구하기 /// </summary> /// <param name="request">요청</param> /// <returns>액션 요청 여부</returns> private bool IsActionRequest(HttpListenerRequest request) { bool isActionRequest = request.Url.AbsolutePath.EndsWith(".action"); return isActionRequest; } #endregion #region 청취하기 - Listen() /// <summary> /// 청취하기 /// </summary> private void Listen() { while(this.isRunning) { HttpListenerContext context = listener.GetContext(); Thread responseThread = new Thread(new ParameterizedThreadStart(Response)); responseThread.IsBackground = true; this.responseThreadList.Add(responseThread); responseThread.Start(new ThreadParameter { Context = context, Thread = responseThread }); } } #endregion #region 응답하기 - Response(parameter) /// <summary> /// 응답하기 /// </summary> /// <param name="parameter">매개 변수</param> private void Response(object parameter) { ThreadParameter threadParameter = parameter as ThreadParameter; HttpListenerContext context = threadParameter.Context; HttpListenerRequest request = context.Request; HttpListenerResponse response = context.Response; try { if(IsDefaultRequest(request)) { string defaultFilePath = Path.Combine(this.rootPath, "index.html"); WriteFile(response, defaultFilePath); } else if(IsFileRequest(request)) { string physicalPath = GetPhysicalPath(request.Url.AbsolutePath); string filePath = Path.Combine(this.rootPath, physicalPath); if(File.Exists(filePath)) { WriteFile(response, filePath); } else { Write(response, string.Format("요청하신 파일이 존재하지 않습니다 : {0}", request.Url.ToString()), true); } } else if(IsActionRequest(request)) { if(ActionRequested != null) { ActionRequested(this, new ActionRequestedEventArgs(this, context)); } else { WriteDefaultAction(context); } } else { Write(response, string.Format("요청하신 URL이 존재하지 않습니다 : {0}", request.Url.ToString()), true); } } catch(Exception e) { Write(response, e.Message + "//" + e.StackTrace, true); } finally { this.responseThreadList.Remove(threadParameter.Thread); response.Close(); } } #endregion } } |
▶ ThreadParameter.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 |
using System.Net; using System.Threading; namespace TestProject { /// <summary> /// 스레드 매개 변수 /// </summary> public class ThreadParameter { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 컨텍스트 - Context /// <summary> /// 컨텍스트 /// </summary> public HttpListenerContext Context { get; set; } #endregion #region 스레드 - Thread /// <summary> /// 스레드 /// </summary> public Thread Thread { get; set; } #endregion } } |
▶ ActionRequestedEventArgs.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 |
using System; using System.Net; namespace TestProject { /// <summary> /// 액션 요청시 이벤트 인자 /// </summary> public class ActionRequestedEventArgs : EventArgs { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 웹 서버 /// </summary> private WebServer server = null; /// <summary> /// HTTP 청취자 컨텍스트 /// </summary> private HttpListenerContext context = null; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 서버 - Server /// <summary> /// 서버 /// </summary> public WebServer Server { get { return this.server; } } #endregion #region 컨텍스트 - Context /// <summary> /// 컨텍스트 /// </summary> public HttpListenerContext Context { get { return this.context; } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - ActionRequestedEventArgs(server, context) /// <summary> /// 생성자 /// </summary> /// <param name="server">서버</param> /// <param name="context">컨텍스트</param> public ActionRequestedEventArgs(WebServer server, HttpListenerContext context) { this.server = server; this.context = context; } #endregion } } |