Microsoft MVP성태의 닷넷 이야기
.NET Framework: 594. C# - WCF wsDualHttpBinding의 ClientBaseAddress 속성 [링크 복사], [링크+제목 복사]
조회: 15462
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 2개 있습니다.)

C# - WCF wsDualHttpBinding의 ClientBaseAddress 속성

지난 글에서,

C# - wsDualHttpBinding WCF 예제 프로그램
; https://www.sysnet.pe.kr/2/0/10984

wsDualHttpBinding이 HTTP 프로토콜 상에서 양방향 통신을 지원한다고 했습니다. 그런데 이게 어떻게 가능한 일일까요? 마법은 없습니다. ^^ 서버가 호출하는 콜백 메서드는 말 그대로 HTTP 호출에 불과합니다. 즉, 클라이언트 측은 HTTP 호출을 받을 수 있는 HTTP 서버 역할의 포트를 열고 있어야 하는 것입니다.

그러니까, 클라이언트가 서비스 측에 다음과 같은 경로로 HTTP 호출을 했을 때,

http://localhost:21430/Service1.svc

해당 서비스 메서드에서 호출하는 콜백 메서드 또한 클라이언트로 다음과 같은 경로의 HTTP 호출을 하는 것입니다.

http://localhost:80/Temporary_Listen_Addresses/.../

근데... 왠지 "Temporary_Listen_Addresses" 문자열이 낯설지 않아 보입니다. 이에 대해 언급하기 전에, 다음의 글을 읽어볼 필요가 있습니다.

IIS의 80 포트를 공유하는 응용 프로그램 만드는 방법
; https://www.sysnet.pe.kr/2/0/1555

그렇습니다. Temporary_Listen_Addresses URL도 마찬가지로 80 포트를 사용하기 때문에 해당 경로를 마음대로 열 수 있는 권한을 갖고 있거나 아니면 netsh로 미리 등록되어 있어야 하는 것입니다. 당연히 마이크로소프트는 WCF 클라이언트 응용 프로그램을 관리자 권한으로 강제하는 것을 원하지 않았기 때문에 윈도우 운영체제에 WCF wsDualHttpBinding을 위한 콜백 주소를 미리 등록시켜 두었습니다. 실제로 "netsh" 명령어를 이용해 이 경로를 확인할 수 있습니다.

C:\WINDOWS\system32>netsh http show urlacl

URL Reservations:
-----------------

...[생략]...

    Reserved URL            : http://+:80/Temporary_Listen_Addresses/
        User: \Everyone
            Listen: Yes
            Delegate: No
            SDDL: D:(A;;GX;;;WD)

...[생략]...

즉, (적어도 Everyone 계정 권한은 가지고 있을) 클라이언트 프로그램은 Temporary_Listen_Addresses 경로 하위에 80 포트로 요청을 대기할 수 있는 것입니다.




좀 더 알아보기 위해 WCF Logging 설정을 해보겠습니다.

    <system.serviceModel>
        ...[생략]...
        <diagnostics>
            <messageLogging
                logEntireMessage="true"
                logMalformedMessages="false"
                logMessagesAtServiceLevel="true"
                logMessagesAtTransportLevel="true"
                maxMessagesToLog="3000"
                maxSizeOfMessageToLog="2000"/>
        </diagnostics>

    </system.serviceModel>


    <system.diagnostics>
        <sources>
            <source name="System.ServiceModel.MessageLogging" switchValue="Verbose">
                <listeners>
                    <add name="messages"
                    type="System.Diagnostics.XmlWriterTraceListener"
                    initializeData="c:\temp\logs\messages.svclog" />
                </listeners>
            </source>
        </sources>
    </system.diagnostics>

이렇게 한 후 dual 바인딩의 WCF 호출을 하면 첫 번째 로그가 다음과 같은 식으로 남습니다.

<E2ETraceEvent xmlns="http://schemas.microsoft.com/2004/06/E2ETraceEvent">
    <System xmlns="http://schemas.microsoft.com/2004/06/windows/eventlog/system">
        ...[생략]...
    </System>
    <ApplicationData>
        <TraceData>
            <DataItem>
                <MessageLogTraceRecord ...[생략]...>
                    <s:Envelope ...[생략]...>
                        <s:Header>
                            <a:Action s:mustUnderstand="1">http://schemas.xmlsoap.org/ws/2005/02/rm/CreateSequenceResponse</a:Action>
                            <a:RelatesTo>urn:uuid:019651c6-28e2-4872-b88f-c3649f4a37c3</a:RelatesTo>
                            <a:To s:mustUnderstand="1">http://testpc/Temporary_Listen_Addresses/47d0d479-a3ad-46e5-9c75-1b9b83f22d95/79c413c9-ae9d-44fb-b825-7249d442f209</a:To>
                        </s:Header>
                        <s:Body>
                            <CreateSequenceResponse xmlns="http://schemas.xmlsoap.org/ws/2005/02/rm">
                                <Identifier>urn:uuid:e01268f5-3c0d-4942-b412-900320a0287b</Identifier>
                                <Accept>
                                    <AcksTo>
                                        <a:Address>http://localhost:21430/Service1.svc</a:Address>
                                    </AcksTo>
                                </Accept>
                            </CreateSequenceResponse>
                        </s:Body>
                    </s:Envelope>
                </MessageLogTraceRecord>
            </DataItem>
        </TraceData>
    </ApplicationData>
</E2ETraceEvent>

보는 바와 같이 처음 호출 시에 클라이언트는 자신의 콜백을 처리할 URL을 서버 측에 헤더로 전달하고 있는 것입니다. URL을 보면,

http://testpc/Temporary_Listen_Addresses/47d0d479-a3ad-46e5-9c75-1b9b83f22d95/79c413c9-ae9d-44fb-b825-7249d442f209

Temporary_Listen_Addresses 하위에 GUID 형식의 주소 2개를 붙였는데요, 아마도 Dual HTTP 바인딩 호출을 하는 또 다른 클라이언트와의 중복 방지를 위해서일 것입니다. 또한 hostname으로 "testpc"가 전달되는 것도 의미가 있습니다. 이 때문에 WCF 서비스 측에서는 역방향 연결을 위해 "testpc"의 IP 주소값에 대한 해석이 가능해야 한다는 것을 짐작할 수 있습니다.

간단하게 이 상황을 재현해 볼 수 있는데요. 가령 VPN 네트워크 환경에서 WCF 서비스를 VPN 내부의 컴퓨터에 설치하고 VPN 외부의 컴퓨터에서 클라이언트를 실행해 보는 것입니다. 그런 경우, VPN 내부의 컴퓨터에서는 "testpc"라는 컴퓨터 명의 IP를 풀이할 수 없기 때문에 호출 예외가 발생합니다.

여기서 재미있는 점이 있는데요. 클라이언트 측의 호출에서 그 상황에 대한 예외가 다음과 같은 메시지로 발생한다는 것입니다.

System.TimeoutException was unhandled
  HResult=-2146233083
  Message=The open operation did not complete within the allotted timeout of 00:00:59.9979992. The time allotted to this operation may have been a portion of a longer timeout.
  Source=mscorlib
  StackTrace:
    Server stack trace: 
       at System.ServiceModel.Channels.ReliableRequestor.ThrowTimeoutException()
       at System.ServiceModel.Channels.ReliableRequestor.Request(TimeSpan timeout)
       at System.ServiceModel.Channels.ClientReliableSession.Open(TimeSpan timeout)
       at System.ServiceModel.Channels.ClientReliableDuplexSessionChannel.OnOpen(TimeSpan timeout)
       at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
       at System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan timeout)
       at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
       at System.ServiceModel.Channels.ServiceChannel.CallOpenOnce.System.ServiceModel.Channels.ServiceChannel.ICallOnce.Call(ServiceChannel channel, TimeSpan timeout)
       at System.ServiceModel.Channels.ServiceChannel.CallOnceManager.CallOnce(TimeSpan timeout, CallOnceManager cascade)
       at System.ServiceModel.Channels.ServiceChannel.EnsureOpened(TimeSpan timeout)
       at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
       at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
       at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
    Exception rethrown at [0]: 
       at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
       at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
       at ConsoleApplication1.ServiceReference1.IService1.GetData(Int32 value)
       at ConsoleApplication1.ServiceReference1.Service1Client.GetData(Int32 value) in C:\...\ConsoleApplication1\Service References\ServiceReference1\Reference.cs:line 130
       at ConsoleApplication1.Program.Main(String[] args) in C:\...\ConsoleApplication1\Program.cs:line 28
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_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.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

이유는 간단합니다. 해당 IService1.GetData 메서드의 코드를 보면,

public string GetData(int value)
{
    IService1Callback _callback = OperationContext.Current.GetCallbackChannel<IService1Callback>();
    {
        Thread.Sleep(value * 1000);

        _callback.Finished(true);
        return string.Format("You entered: {0}", value);
    }
}

_callback.Finished 호출이 발생하는 데 그 순간 Socket.Connect("testpc") 호출이 발생하지만 "testpc"에 대한 IP 해석이 되지 않아 Socket Connection timeout이 발생하기까지 대기하게 되고 이 때문에 WCF의 기본 timeout 값에 걸려 "The open operation did not complete within the allotted timeout of 00:00:59.9979992"와 같은 오류 메시지가 발생하는 것입니다.

경험이 없는 WCF 개발자라면, 이 오류 메시지를 보고 WCF timeout 관련 설정을 조정하겠지만 그것으로 해결될 문제가 아닙니다. 더욱 문제는, 이에 대해 WCF를 호스팅하는 IIS 서비스 측에서 이벤트 로그 등을 통한 오류 흔적이 전혀 안 남는다는 점입니다.

이 오류를 쉽게 감지하는 것은 WCF 로깅을 사용하거나 지난번에 알려드린 procdump를 이용해 보면 됩니다.

try/catch로 조용히 사라진 예외를 파악하고 싶다면?
; https://www.sysnet.pe.kr/2/0/10965

가령, procdump.exe를 이용하는 경우 다음과 같은 오류 메시지가 발생하는 것을 확인할 수 있습니다.

[21:05:05] Exception: E0434F4D.System.Net.WebException ("The remote name could not be resolved: 'testpc'")
[21:05:05] Exception: E0434F4D.System.ServiceModel.EndpointNotFoundException ("There was no endpoint listening at http://testpc/Temporary_Listen_Addresses/1f1be8f1-d610-4797-840c-07ebdbfd3ad1/7e5a35b9-1d00-4a15-9a46-585798e347da that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.")
[21:05:05] Exception: E0434F4D.System.ServiceModel.CommunicationException ("The inactivity timeout of (00:10:00) has been exceeded.")
[21:05:05] Exception: E0434F4D.System.ServiceModel.CommunicationObjectFaultedException ("The communication object, System.ServiceModel.Channels.ServerReliableDuplexSessionChannel, cannot be used for communication because it is in the Faulted state.")




바로 이런 경우처럼, WCF가 자동으로 넘겨주는 "Temporary_Listen_Addresses" 주소를 WCF 서비스 측에서 콜백 호출 시 아무런 문제가 없도록 하는 방법이 ClientBaseAddress를 지정해 주는 것입니다.

이 글의 예에서는 VPN에 알려진 클라이언트 측의 IP 주소를 192.168.10.22라고 가정했을 때 다음과 같이 바인딩 정보를 지정하면 됩니다.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>
    <system.serviceModel>
        <bindings>
            <wsDualHttpBinding>
                <binding name="WSDualHttpBinding_IService1" 
                    clientBaseAddress="http://192.168.10.22/Temporary_Listen_Addresses/">
                    <security mode="None" />
                </binding>
            </wsDualHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://192.168.10.55:8033/Service1.svc" binding="wsDualHttpBinding"
                bindingConfiguration="WSDualHttpBinding_IService1" contract="ServiceReference1.IService1"
                name="WSDualHttpBinding_IService1" />
        </client>
    </system.serviceModel>
</configuration>

이렇게 바꾸고 WCF 호출을 하면, 서버 측에서는 클라이언트가 새롭게 전달해 준 "http://192.168.10.22/Temporary_Listen_Addresses/.../..." 주소로 역방향 호출을 하게 되고 결과적으로 서비스가 정상적으로 운영이 됩니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/10/2021]

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

비밀번호

댓글 작성자
 




[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13600정성태4/18/2024249닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024271닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024284닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드1
13597정성태4/15/2024361닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/2024715닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/2024839닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241000닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241049닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241202C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241164닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241071Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241140닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241191닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신파일 다운로드1
13587정성태3/27/20241149오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241293Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241094Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241046개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241149Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241407Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
13581정성태3/18/20241585개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
13580정성태3/15/20241136닷넷: 2231. C# - ReceiveTimeout, SendTimeout이 적용되지 않는 Socket await 비동기 호출파일 다운로드1
13579정성태3/13/20241493오류 유형: 899. HTTP Error 500.32 - ANCM Failed to Load dll
13578정성태3/11/20241628닷넷: 2230. C# - 덮어쓰기 가능한 환형 큐 (Circular queue)파일 다운로드1
13577정성태3/9/20241870닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx)
13576정성태3/8/20241543닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...