Microsoft MVP성태의 닷넷 이야기
.NET Framework: 594. C# - WCF wsDualHttpBinding의 ClientBaseAddress 속성 [링크 복사], [링크+제목 복사]
조회: 15514
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




... 46  47  48  [49]  50  51  52  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12401정성태11/5/202010452VS.NET IDE: 153. 닷넷 응용 프로그램에서의 "My Code" 범위와 "Enable Just My Code"의 역할 [1]
12400정성태11/5/20207503오류 유형: 679. Visual Studio - "Source Not Found" 창에 "Decompile source code" 링크가 없는 경우
12399정성태11/5/202011113.NET Framework: 961. C# 9.0 - (10) 대상으로 형식화된 조건식(Target-typed conditional expressions)파일 다운로드1
12398정성태11/4/20209562오류 유형: 678. Windows Server 2008 R2 환경에서 Powershell을 psexec로 원격 실행할 때 hang이 발생하는 문제
12397정성태11/4/20209702.NET Framework: 960. C# - 조건 연산자(?:)를 사용하는 경우 달라지는 메서드 선택 사례파일 다운로드1
12396정성태11/3/20208123VS.NET IDE: 152. Visual Studio - "Tools" / "External Tools..."에 등록된 외부 명령어에 대한 단축키 설정 방법
12395정성태11/3/20209401오류 유형: 677. SSMS로 DB 접근 시 The server principal "..." is not able to access the database "..." under the current security context.
12394정성태11/3/20207831오류 유형: 676. cacls - The Recycle Bin on ... is corrupted. Do you want to empty the Recycle Bin for this drive?
12393정성태11/3/20208313오류 유형: 675. Visual Studio - 닷넷 응용 프로그램 디버깅 시 Disassembly 창에서 BP 설정할 때 "Error while processing breakpoint." 오류
12392정성태11/2/202012426.NET Framework: 959. C# 9.0 - (9) 레코드(Records) [4]파일 다운로드1
12390정성태11/1/202010548디버깅 기술: 173. windbg - System.Configuration.ConfigurationErrorsException 예외 분석 방법
12389정성태11/1/202010483.NET Framework: 958. C# 9.0 - (8) 정적 익명 함수 (static anonymous functions)파일 다운로드1
12388정성태10/29/20209854오류 유형: 674. 어느 순간부터 닷넷 응용 프로그램 실행 시 System.Configuration.ConfigurationErrorsException 예외가 발생한다면?
12387정성태10/28/202010568.NET Framework: 957. C# - static 필드의 정보가 GC Heap에 저장될까요? [3]파일 다운로드1
12386정성태10/28/202010846Linux: 34. 사용자 정보를 함께 출력하는 리눅스의 ps 명령어 사용 방법
12385정성태10/28/20208592오류 유형: 673. openssl - req: No value provided for Subject Attribute CN, skipped
12384정성태10/27/20209818오류 유형: 672. AllowPartiallyTrustedCallers 특성이 적용된 어셈블리의 struct 멤버 메서드를 재정의하면 System.Security.VerificationException 예외 발생
12383정성태10/27/202010836.NET Framework: 956. C# 9.0 - (7) 패턴 일치 개선 사항(Pattern matching enhancements) [3]파일 다운로드1
12382정성태10/26/20208458오류 유형: 671. dotnet build - The local source '...' doesn't exist
12381정성태10/26/202010113VC++: 137. C++ stl map의 사용자 정의 타입을 key로 사용하는 방법 [1]파일 다운로드1
12380정성태10/26/20207614오류 유형: 670. Visual Studio - Squash_FailureCommitsReset
12379정성태10/21/202010507.NET Framework: 955. .NET 메서드의 Signature 바이트 코드 분석 [1]파일 다운로드2
12378정성태10/15/20209987.NET Framework: 954. C# - x86/x64 환경에 따라 달라지는 P/Invoke 함수의 export 이름파일 다운로드1
12377정성태10/15/202011329디버깅 기술: 172. windbg - 파일 열기 시점에 bp를 걸어 파일명 알아내는 방법(Managed/Unmanaged)
12376정성태10/15/20208083오류 유형: 669. windbg - sos의 name2ee 명령어 실행 시 "Failed to request module list." 오류
12375정성태10/15/20209442Windows: 177. 윈도우 탐색기에서 띄우는 cmd.exe 창의 디렉터리 구분 문자가 'Yen(&#0165;)' 기호로 나오는 경우 [1]
... 46  47  48  [49]  50  51  52  53  54  55  56  57  58  59  60  ...