성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] Get Started with Milvus Vector DB i...
[정성태] cyberark/PipeViewer - A tool that...
[정성태] WinForms in a 64-Bit world – our st...
[정성태] 예제에서 SELECT_SQL도 내부적으로는 SqlCommand/...
[victor] SELECT_LINQ SELECT_SQL 같은 쿼리인...
[victor] 답변 갑사합니다. 예외(Exception)가 났습니다. ...
[정성태] 일단, 위의 방식대로 하면 예외(Exception) 없이 잘 동...
[정성태] Windows 10 (버전 1809)에 이런 기능이 ^^ 추가되...
[정성태] pde windbg extension ; https://lea...
[정성태] // GetEnumerator extensions for Ran...
글쓰기
제목
이름
암호
전자우편
HTML
홈페이지
유형
제니퍼 .NET
닷넷
COM 개체 관련
스크립트
VC++
VS.NET IDE
Windows
Team Foundation Server
디버깅 기술
오류 유형
개발 환경 구성
웹
기타
Linux
Java
DDK
Math
Phone
Graphics
사물인터넷
부모글 보이기/감추기
내용
<div style='display: inline'> <h1 style='font-family: Malgun Gothic, Consolas; font-size: 20pt; color: #006699; text-align: center; font-weight: bold'>C# - HttpWebRequest, WebClient와 ephemeral port 재사용</h1> <p> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > 이 글의 테스트는 .NET Framework 4.8 + Windows 10에서 진행했고, 결과는 환경마다 다를 수 있습니다. </pre> <br /> 지난 글에서,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > 윈도우 서버 환경에서, 최대 생성 가능한 소켓(socket) 연결 수는 얼마일까? ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/964'>https://www.sysnet.pe.kr/2/0/964</a> 윈도우 환경에서 클라이언트 소켓의 최대 접속 수 ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12350'>https://www.sysnet.pe.kr/2/0/12350</a> 윈도우 환경에서 클라이언트 소켓의 최대 접속 수 (2) - SO_REUSEADDR ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12432'>https://www.sysnet.pe.kr/2/0/12432</a> 윈도우 환경에서 클라이언트 소켓의 최대 접속 수 (3) - SO_PORT_SCALABILITY ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12433'>https://www.sysnet.pe.kr/2/0/12433</a> 윈도우 환경에서 클라이언트 소켓의 최대 접속 수 (4) - ReuseUnicastPort를 이용한 포트 고갈 문제 해결 ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12435'>https://www.sysnet.pe.kr/2/0/12435</a> </pre> <br /> 계속 5-tuple 구분 문제를 다뤘는데요, 그렇다면 닷넷 개발자에게는 이것이 어떤 의미가 있을까요?<br /> <br /> 우선, 닷넷의 경우에도 소켓을 직접 다룬다면 위의 내용이 그대로 적용됩니다. (사실, 위의 글에서 모두 .NET의 Socket 클래스로 예제를 만들었습니다.) 따라서 AutoReusePortRangeStartPort 혜택을 누리기 위해 bind를 직접 하는 경우에만 SocketOptionName.ReuseUnicastPort 옵션을 미리 설정해 주면 됩니다.<br /> <br /> 그렇다면 HttpWebRequest는 어떨까요? 어쩌면 HttpWebRequest에서 내부적으로 감싸고 있는 Socket 인스턴스가 명시적인 바인딩은 하지만 SocketOptionName.ReuseUnicastPort 옵션을 설정하지 않고 있을지도 모릅니다.<br /> <br /> 이를 명확히 하기 위해 ^^ 당연히 테스트를 해야겠지요.<br /> <br /> <hr style='width: 50%' /><br /> <br /> 환경 구성은 <a target='tab' href='https://www.sysnet.pe.kr/2/0/12435'>지난 글</a>에 했던 시스템을 그대로 재사용하겠습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > DynamicPortRangeStartPort : 1024 DynamicPortRangeNumberOfPorts : 977 AutoReusePortRangeStartPort : 15000 AutoReusePortRangeNumberOfPorts : 1000 </pre> <br /> 그리고 서버 코드는 그대로 두고, 클라이언트 측만 Socket을 HttpWebRequest로 바꿔보겠습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > using System; using System.Collections.Concurrent; using System.Diagnostics; using System.Net; using System.Threading; namespace ConsoleApp2 { class Program { static void Main(string[] args) { string ipAddr = args[0]; int port = int.Parse(args[1]); int numberOf = int.Parse(args[2]); ThreadPool.SetMaxThreads(1100, 1100); ThreadPool.SetMinThreads(1000, 1000); ConcurrentQueue<HttpWebRequest> clients1 = new ConcurrentQueue<HttpWebRequest>(); Uri uri = new Uri($"http://{ipAddr}:{port}"); int exceptionCount = 0; for (int i = 0; i < numberOf; i++) { ThreadPool.QueueUserWorkItem((WaitCallback)((obj) => { var request = (HttpWebRequest)WebRequest.Create(uri); clients1.Enqueue(request); try { request.GetResponse(); } catch { Interlocked.Increment(ref exceptionCount); } }), null); } while (true) { Console.WriteLine("Pid == " + Process.GetCurrentProcess().Id); Console.ReadLine(); } } } } </pre> <br /> 이렇게 해서 실행해 보면, 다음과 같은 결과를 얻습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > // 서버 측 포트 17000, 17001 Listen D:\temp> <span style='color: blue; font-weight: bold'>ConsoleApp1</span> # of 17000: 0, 17001: 0 # of 17000: 0, 17001: 0 # of 17000: 1, 17001: 0 # of 17000: 1000, 17001: 1 # of 17000: 1000, 17001: 1000 # of 17000: 1000, 17001: 1000 # of 17000: 1000, 17001: 1000 <span style='color: blue; font-weight: bold'># of 17000: 1000, 17001: 1000</span> </pre> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > // #1 클라이언트 측 - 17000 포트로 1001개 접속 시도 // ConsoleApp2.exe localhost 17000 1001 C:\temp> <span style='color: blue; font-weight: bold'>netstat -ano | findstr 5748</span> TCP 127.0.0.1:15161 127.0.0.1:17000 ESTABLISHED 5748 TCP 127.0.0.1:15162 127.0.0.1:17000 ESTABLISHED 5748 TCP 127.0.0.1:15163 127.0.0.1:17000 ESTABLISHED 5748 TCP 127.0.0.1:15164 127.0.0.1:17000 ESTABLISHED 5748 ...[생략]... TCP 127.0.0.1:15996 127.0.0.1:17000 ESTABLISHED 5748 TCP 127.0.0.1:15997 127.0.0.1:17000 ESTABLISHED 5748 TCP 127.0.0.1:15998 127.0.0.1:17000 ESTABLISHED 5748 TCP 127.0.0.1:15999 127.0.0.1:17000 ESTABLISHED 5748 </pre> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > // #2 클라이언트 측 - 17001 포트로 1001개 접속 시도 // ConsoleApp2.exe localhost 17001 1001 C:\Users\kevin> <span style='color: blue; font-weight: bold'>netstat -ano | findstr 8364</span> TCP 127.0.0.1:15079 127.0.0.1:17001 ESTABLISHED 8364 TCP 127.0.0.1:15080 127.0.0.1:17001 ESTABLISHED 8364 TCP 127.0.0.1:15081 127.0.0.1:17001 ESTABLISHED 8364 TCP 127.0.0.1:15082 127.0.0.1:17001 ESTABLISHED 8364 ...[생략]... TCP 127.0.0.1:15996 127.0.0.1:17001 ESTABLISHED 8364 TCP 127.0.0.1:15997 127.0.0.1:17001 ESTABLISHED 8364 TCP 127.0.0.1:15998 127.0.0.1:17001 ESTABLISHED 8364 TCP 127.0.0.1:15999 127.0.0.1:17001 ESTABLISHED 8364 </pre> <br /> (아쉽게도 HttpWebRequest는 직접 Socket 인스턴스를 노출시키지 않으므로 확인 과정은 netstat를 이용했습니다.)<br /> <br /> 결과를 보면, HttpWebRequest는 ReuseUnicastPort를 이용하도록 설계되어 있다는 것을 알 수 있습니다. 따라서 그냥 윈도우 환경 설정만 잘 해주시면 끝!<br /> <br /> (<a href='https://www.sysnet.pe.kr/bbs/DownloadAttachment.aspx?fid=1678&boardid=331301885'>첨부 파일은 이 글의 예제 코드를 포함</a>합니다.)<br /> <br /> <hr style='width: 50%' /><br /> <br /> 그런데, 약간 혼란스러운 문서가 하나 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > ServicePointManager.ReusePort Property ; <a target='tab' href='https://learn.microsoft.com/en-us/dotnet/api/system.net.servicepointmanager.reuseport'>https://learn.microsoft.com/en-us/dotnet/api/system.net.servicepointmanager.reuseport</a> </pre> <br /> <div style='BACKGROUND-COLOR: #ccffcc; padding: 10px 10px 5px 10px; MARGIN: 0px 10px 10px 10px; FONT-FAMILY: Malgun Gothic, Consolas, Verdana; COLOR: #005555'> Setting this property value to true causes all outbound TCP connections from HttpWebRequest to use the native socket option SO_REUSE_UNICASTPORT on the socket. This causes the underlying outgoing ports to be shared. This is useful for scenarios where a large number of outgoing connections are made in a short time, and the app risks running out of ports.<br /> </div><br /> <br /> 즉, 원래 저런 식으로 SO_REUSE_UNICASTPORT 옵션이 적용된 동작은 ServicePointManager.ReusePort 속성(기본값: False)을 True로 한 경우라고 합니다. 하지만, 제가 테스트한 Windows 10 + .NET 4.8 환경에서는 ReusePort 속성의 값에 아무런 상관이 없었습니다. (혹시, ReusePort 속성에 관한 차이점을 아시는 분은 덧글 부탁드립니다.)<br /> <br /> <hr style='width: 50%' /><br /> <br /> WebClient는 내부적으로 HttpWebRequest를 사용하기 때문에 사실 테스트할 필요도 없을 것 같지만, 그래도 정 원한다면 위의 HttpWebRequest 예제에서 다음과 같이 살짝 WebClient로 교체만 한 후,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > ConcurrentQueue<WebClient> clients1 = new ConcurrentQueue<WebClient>(); Uri uri = new Uri($"http://{ipAddr}:{port}"); int exceptionCount = 0; for (int i = 0; i < numberOf; i++) { ThreadPool.QueueUserWorkItem((WaitCallback)((obj) => { WebClient wc = new WebClient(); clients1.Enqueue(wc); try { wc.DownloadString(uri); } catch { Interlocked.Increment(ref exceptionCount); } }), null); } </pre> <br /> 테스트하면 HttpWebRequest와 정확히 같은 결과를 얻는 것을 확인할 수 있습니다.<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
1624
(왼쪽의 숫자를 입력해야 합니다.)