Microsoft MVP성태의 닷넷 이야기
.NET Framework: 569. ServicePointManager.DefaultConnectionLimit의 역할 [링크 복사], [링크+제목 복사],
조회: 24154
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 2개 있습니다.)

ServicePointManager.DefaultConnectionLimit의 역할

지난번 글에서 ServicePointManager.DefaultConnectionLimit 값을 설정하는 방법에 대해 알아봤는데요.

System.Net.ServicePointManager의 DefaultConnectionLimit 속성 설명
; https://www.sysnet.pe.kr/2/0/10927

그럼 도대체, ConnectionLimit가 어떤 역할을 하느냐... 하는 사항이 궁금할 것입니다. 그냥 간단하게는 HttpWebRequest 객체에 대한 "소켓 Connection Pooling"과 같은 의미라고 보시면 됩니다. (WebClient와 같은 객체도 결국 내부적으로 HttpWebRequest를 사용하기 때문에 같은 제약을 받습니다.)

예를 들어 보면, 여러분들의 응용 프로그램에서 HttpWebRequest를 이용해 특정 웹 서버로 요청/응답을 받는 코드가 있다고 가정해 보겠습니다. 만약 스레드 2개로 HttpWebRequest를 동시에 각각 생성해 테스트하면 DefaultConnectionLimit의 값이 2인 경우 정상적으로 처리를 하게 됩니다. 하지만, 스레드를 3개로 해서 HttpWebRequest를 3개 생성해 웹 요청을 처리하려고 하면 DefaultConnectionLimit의 값이 2인 경우 3번째 HttpWebRequest는 먼저 생성된 2개의 HttpWebRequest 중 하나의 요청이 끝나야만 동작을 하게 됩니다.

단일 스레드 위주로 돌아가는 클라이언트 응용 프로그램이라면 이런 것이 크게 문제가 되지 않는데, 웹 서버라면 상황이 다릅니다. 만약 default.aspx 페이지 같은 곳에서 다른 서버로 HttpWebRequest를 이용해 요청 처리를 하는 코드가 있다면 ASP.NET 2.0의 경우 "Core가 2개"라면 총 24개의 HttpWebRequest 객체만 동시에 활성화시킬 수 있습니다. 이는 곧, default.aspx에 사용자의 요청이 24개만 동시처리되고 나머지는 스레드가 블럭된다는 것을 의미합니다.

정말 그런지... 한번 테스트를 해볼까요? ^^

일단, 웹 요청을 지연 처리해줄 간단한 웹 서버를 소켓 프로그램으로 만들겠습니다.

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace SlowHttpServer
{
    class Program
    {
        static void Main(string[] args)
        {
            using (Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8035));
                serverSocket.Listen(5);

                while (true)
                {
                    Socket socket = serverSocket.Accept();
                    ThreadPool.QueueUserWorkItem(processChildSocket, socket);
                }
            }
        }

        static int _count = 0;

        private static void processChildSocket(object state)
        {
            int idx = Interlocked.Increment(ref _count);

            using (Socket child = state as Socket)
            {
                byte[] buf = new byte[8192];
                int len = child.Receive(buf);

                string txt = Encoding.UTF8.GetString(buf, 0, len);
                Console.WriteLine("[" + idx + "]" + DateTime.Now + Environment.NewLine + txt);

                int delay = GetDelayTime(txt);

                byte[] responseBuf = GetResponseData(delay);

                child.Send(responseBuf);
                child.Close();
            }
        }

        private static int GetDelayTime(string txt)
        {
            StringReader sr = new StringReader(txt);
            int sleep = 0;
            while (true)
            {
                string line = sr.ReadLine();

                if (line == null)
                {
                    break;
                }

                int pos = line.IndexOf("Delay");
                if (pos == -1)
                {
                    continue;
                }

                int colonPos = line.IndexOf(":");
                if (colonPos == -1)
                {
                    continue;
                }

                sleep = Int32.Parse(line.Substring(colonPos + 1));
            }

            return sleep;
        }

        private static byte[] GetResponseData(int delay)
        {
            DateTime now = DateTime.Now;
            Thread.Sleep(delay);
            DateTime after = DateTime.Now;

            string header = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n";
            string body = "<html><body><mark>" + now + "<br />\r\n" + after + "<br />\r\n HTML</mark> 웹 페이지입니다.</body></html>";
            byte[] respBuf = Encoding.UTF8.GetBytes(header + body);
            return respBuf;
        }
    }
}

위의 프로그램은 HTTP 헤더에 Delay 키를 포함해 전송해주면 그것의 값만큼 지연을 시켜 응답을 보냅니다. 이제 클라이언트 콘솔 응용 프로그램을 만들고 다음과 같이 동시에 3개의 요청을 보내는 코드를 추가합니다.

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static string _url = "http://test.mypc.com:8035";
        static int _count = 0;

        static void Main(string[] args)
        {
            Console.WriteLine("DefaultConnectionLimit: " + System.Net.ServicePointManager.DefaultConnectionLimit);
            Console.WriteLine("DefaultPersistentConnectionLimit: " + System.Net.ServicePointManager.DefaultPersistentConnectionLimit);

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();

            ThreadPool.SetMinThreads(100, 100);

            int reqCount = 3;

            for (int i = 0; i < reqCount; i ++)
            {
                ThreadPool.QueueUserWorkItem(requestHttp, null);
            }

            Console.ReadLine();
        }

        private static void requestHttp(object state)
        {
            int idx = Interlocked.Increment(ref _count);
            Thread.CurrentThread.Name = string.Format("request #{0}", idx);

            HttpWebRequest req = HttpWebRequest.CreateHttp(_url);
            {
                req.Headers.Add("Delay", "5000");
                req.ServicePoint.Expect100Continue = false;

                Console.WriteLine(DateTime.Now + " Request: " + idx + " - Begin");
                HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
                Console.WriteLine(DateTime.Now + " Request: " + idx + " - End");

                WriteLine(DateTime.Now + " Request: " + idx);

                using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
                {
                    sr.ReadToEnd();
                }
            }
        }
    }
}

실행하기 전, "C:\Windows\System32\drivers\etc\HOSTS" 파일에 "test.mypc.com" 을 "127.0.0.1"로 등록해 줍니다.

127.0.0.1 test.mypc.com

이렇게 하고 실행하면 서버는 다음과 같이 출력하고,

C:\...\SlowHttpServer\bin\Debug>SlowHttpServer.exe
[2]2016-03-28 오후 11:46:43
GET / HTTP/1.1
Delay: 5000
Host: test.mypc.com:8035
Connection: Keep-Alive


[1]2016-03-28 오후 11:46:43
GET / HTTP/1.1
Delay: 5000
Host: test.mypc.com:8035
Connection: Keep-Alive


[3]2016-03-28 오후 11:46:48
GET / HTTP/1.1
Delay: 5000
Host: test.mypc.com:8035

클라이언트는 이런 식으로 출력합니다.

DefaultConnectionLimit: 2
DefaultPersistentConnectionLimit: 2


2016-03-28 오후 11:46:43 Request: 1 - Begin
2016-03-28 오후 11:46:43 Request: 2 - Begin
2016-03-28 오후 11:46:43 Request: 3 - Begin
2016-03-28 오후 11:46:48 Request: 3 - End
2016-03-28 오후 11:46:48 Request: 1 - End
2016-03-28 오후 11:46:53 Request: 2 - End

먼저 클라이언트의 출력 결과를 보면, 1번과 3번 스레드의 HttpWebRequest가 End가 되고 나서야 2번 스레드의 HttpWebRequest가 5초 후에 완료되는 것을 볼 수 있습니다. 이와 함께 서버 측의 로그에는 11:46:43초에 2개의 요청을 받고 5초 동안 지연된 다음 응답을 완료했고 세 번째 요청 처리를 11:46:48초에 한 것으로 나옵니다.

즉, 2개의 요청만 동시 처리되고 1개의 요청은 DefaultConnectionLimit == 2의 설정으로 인해 동시 처리되지 않은 것입니다. (일반적인 닷넷 콘솔 프로그램의 DefaultConnectionLimit의 기본값이 2입니다.)




자... 이제 그럼 ServicePoint에 대해 알아볼 차례입니다. 사실 단어가 좀 낯설어서 그렇지, ServicePoint 하나는 고유 URL 하나에 대응해 생성하는 객체입니다. 가령, HttpWebRequest로 "http://test.mypc.com:8035", "http://pc.mytest.com:8035", "http://my.pc.com:8035" 3개에 대해 요청을 발생시키면 각각의 URL 마다 ServicePoint 객체가 생성되고 이것들 역시 Pool 형태로 ServicePointManager에 의해 관리가 됩니다.

ServicePointManager가 생성할 수 있는 최대 ServicePoint의 수는 "System.Net.ServicePointManager.MaxServicePoints" 속성을 보면 되는데, 기본값은 0 이어서 닷넷 프로그램에서 생성할 수 있는 ServicePoint의 수에 제한이 없습니다. 그런데, 테스트를 위해 이 값을 1로 주면 어떻게 될까요? 이 상태에서 다음과 같은 요청을 (동시에 또는 차례대로) 보내면,

HttpWebRequest: http://test.mypc.com:8035
HttpWebRequest: http://test.mypc.com:8035
HttpWebRequest: http://test.mypc.com:8035

ServicePointManager는 1개의 ServicePoint를 생성하고, 그 객체 안에서 3개의 연결을 모두 처리합니다. 반면, 다음과 같이 요청을 보내면,

HttpWebRequest: http://test.mypc.com:8035
HttpWebRequest: http://test.mypc.com:8035
HttpWebRequest: http://pc.mytest.com:8035

2번째 요청까지는 ServicePointManager가 생성한 1개의 ServicePoint에서 처리하지만, 3번째 요청에서 전혀 다른 URL이 들어와서 그에 대한 ServicePoint를 생성하려 하지만 ServicePointManager.MaxServicePoints == 1의 제약에 걸려 다음과 같은 예외를 던지고 맙니다.

System.InvalidOperationException was unhandled
  HResult=-2146233079
  Message=The maximum number of service points was exceeded.
  Source=System
  StackTrace:
       at System.Net.ServicePointManager.FindServicePointHelper(Uri address, Boolean isProxyServicePoint)
       at System.Net.ServicePointManager.FindServicePoint(Uri address, IWebProxy proxy, ProxyChain& chain, HttpAbortDelegate& abortDelegate, Int32& abortState)
       at System.Net.HttpWebRequest.FindServicePoint(Boolean forceFind)
       at System.Net.HttpWebRequest.GetResponse()
       at ConsoleApplication1.Program.requestHttp(Object state) in C:\...\ConsoleApplication1\Program.cs:line 81
       at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
       at System.Threading.ThreadPoolWorkQueue.Dispatch()
       at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
  InnerException: 

현실적으로 봤을 때, 대부분의 닷넷 개발자들이 ServicePointManager.MaxServicePoints의 수치를 조정하지 않기 때문에 사실 저 예외를 만날 일은 거의 없습니다.




정리해 보면, ServicePointManager는 고유 URL 마다 1개의 ServicePoint를 생성합니다. 그리고 그 각각의 ServicePoint는 내부에 N 개의 연결을 관리합니다. 즉, 다음과 같이 1:N의 관계입니다.

ServicePointManager 1 : N ServicePoint
ServicePoint 1 : N Connection

(첨부한 파일은 이 글의 예제 코드를 포함합니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 6/27/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 46  47  48  49  50  51  52  53  54  55  56  57  58  59  [60]  ...
NoWriterDateCnt.TitleFile(s)
12129정성태1/26/202015311.NET Framework: 882. C# - 키움 Open API+ 사용 시 Registry 등록 없이 KHOpenAPI.ocx 사용하는 방법 [3]
12128정성태1/26/202010105오류 유형: 591. The code execution cannot proceed because mfc100.dll was not found. Reinstalling the program may fix this problem.
12127정성태1/25/20209980.NET Framework: 881. C# DLL에서 제공하는 Win32 export 함수의 내부 동작 방식(VT Fix up Table)파일 다운로드1
12126정성태1/25/202010797.NET Framework: 880. C# - PE 파일로부터 IMAGE_COR20_HEADER 및 VTableFixups 테이블 분석파일 다운로드1
12125정성태1/24/20208684VS.NET IDE: 141. IDE0019 - Use pattern matching
12124정성태1/23/202010508VS.NET IDE: 140. IDE1006 - Naming rule violation: These words must begin with upper case characters: ...
12123정성태1/23/202011980웹: 39. Google Analytics - gtag 함수를 이용해 페이지 URL 수정 및 별도의 이벤트 생성 방법 [2]
12122정성태1/20/20208981.NET Framework: 879. C/C++의 UNREFERENCED_PARAMETER 매크로를 C#에서 우회하는 방법(IDE0060 - Remove unused parameter '...')파일 다운로드1
12121정성태1/20/20209555VS.NET IDE: 139. Visual Studio - Error List: "Could not find schema information for the ..."파일 다운로드1
12120정성태1/19/202010967.NET Framework: 878. C# DLL에서 Win32 C/C++처럼 dllexport 함수를 제공하는 방법 - 네 번째 이야기(IL 코드로 직접 구현)파일 다운로드1
12119정성태1/17/202010993디버깅 기술: 160. Windbg 확장 DLL 만들기 (3) - C#으로 만드는 방법
12118정성태1/17/202011638개발 환경 구성: 466. C# DLL에서 Win32 C/C++처럼 dllexport 함수를 제공하는 방법 - 세 번째 이야기 [1]
12117정성태1/15/202010631디버깅 기술: 159. C# - 디버깅 중인 프로세스를 강제로 다른 디버거에서 연결하는 방법파일 다운로드1
12116정성태1/15/202011101디버깅 기술: 158. Visual Studio로 디버깅 시 sos.dll 확장 명령어를 (비롯한 windbg의 다양한 기능을) 수행하는 방법
12115정성태1/14/202010881디버깅 기술: 157. C# - PEB.ProcessHeap을 이용해 디버깅 중인지 확인하는 방법파일 다운로드1
12114정성태1/13/202012745디버깅 기술: 156. C# - PDB 파일로부터 심벌(Symbol) 및 타입(Type) 정보 열거 [1]파일 다운로드3
12113정성태1/12/202013363오류 유형: 590. Visual C++ 빌드 오류 - fatal error LNK1104: cannot open file 'atls.lib' [1]
12112정성태1/12/20209970오류 유형: 589. PowerShell - 원격 Invoke-Command 실행 시 "WinRM cannot complete the operation" 오류 발생
12111정성태1/12/202013191디버깅 기술: 155. C# - KernelMemoryIO 드라이버를 이용해 실행 프로그램을 숨기는 방법(DKOM: Direct Kernel Object Modification) [16]파일 다운로드1
12110정성태1/11/202011796디버깅 기술: 154. Patch Guard로 인해 블루 스크린(BSOD)가 발생하는 사례 [5]파일 다운로드1
12109정성태1/10/20209716오류 유형: 588. Driver 프로젝트 빌드 오류 - Inf2Cat error -2: "Inf2Cat, signability test failed."
12108정성태1/10/20209726오류 유형: 587. Kernel Driver 시작 시 127(The specified procedure could not be found.) 오류 메시지 발생
12107정성태1/10/202010688.NET Framework: 877. C# - 프로세스의 모든 핸들을 열람 - 두 번째 이야기
12106정성태1/8/202012117VC++: 136. C++ - OSR Driver Loader와 같은 Legacy 커널 드라이버 설치 프로그램 제작 [1]
12105정성태1/8/202010745디버깅 기술: 153. C# - PEB를 조작해 로드된 DLL을 숨기는 방법
12104정성태1/7/202011455DDK: 9. 커널 메모리를 읽고 쓰는 NT Legacy driver와 C# 클라이언트 프로그램 [4]
... 46  47  48  49  50  51  52  53  54  55  56  57  58  59  [60]  ...