Microsoft MVP성태의 닷넷 이야기
.NET Framework: 594. C# - WCF wsDualHttpBinding의 ClientBaseAddress 속성 [링크 복사], [링크+제목 복사]
조회: 15484
글쓴 사람
정성태 (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)
12221정성태6/3/20209772Windows: 170. 비어 있지 않은 디렉터리로 symbolic link(junction) 연결하는 방법
12220정성태6/3/202012141.NET Framework: 907. C# DLL로부터 TLB 및 C/C++ 헤더 파일(TLH)을 생성하는 방법
12219정성태6/1/202011282.NET Framework: 906. C# - lock (this), lock (typeof(...))를 사용하면 안 되는 이유파일 다운로드1
12218정성태5/27/202011220.NET Framework: 905. C# - DirectX 게임 클라이언트 실행 중 키보드 입력을 감지하는 방법 [3]
12217정성태5/24/20209711오류 유형: 615. Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 0, current count = 1.
12216정성태5/15/202012822.NET Framework: 904. USB/IP PROJECT를 이용해 C#으로 USB Keyboard 가상 장치 만들기 [14]파일 다운로드1
12215정성태5/12/202017797개발 환경 구성: 490. C# - (Wireshark의) USBPcap을 이용한 USB 패킷 모니터링 [10]파일 다운로드1
12214정성태5/5/202010199개발 환경 구성: 489. 정식 인증서가 있는 경우 Device Driver 서명하는 방법 (2) - UEFI/SecureBoot [1]
12213정성태5/3/202011820개발 환경 구성: 488. (User-mode 코드로 가상 USB 장치를 만들 수 있는) USB/IP PROJECT 소개
12212정성태5/1/20209487개발 환경 구성: 487. UEFI / Secure Boot 상태인지 확인하는 방법
12211정성태4/27/202011822개발 환경 구성: 486. WSL에서 Makefile로 공개된 리눅스 환경의 C/C++ 소스 코드 빌드
12210정성태4/20/202012208.NET Framework: 903. .NET Framework의 Strong-named 어셈블리 바인딩 (1) - app.config을 이용한 바인딩 리디렉션 [1]파일 다운로드1
12209정성태4/13/202010303오류 유형: 614. 리눅스 환경에서 C/C++ 프로그램이 Segmentation fault 에러가 발생한 경우 (2)
12208정성태4/12/20209812Linux: 29. 리눅스 환경에서 C/C++ 프로그램이 Segmentation fault 에러가 발생한 경우
12207정성태4/2/20208792스크립트: 19. Windows PowerShell의 NonInteractive 모드
12206정성태4/2/202011026오류 유형: 613. 파일 잠금이 바로 안 풀린다면? - The process cannot access the file '...' because it is being used by another process.
12205정성태4/2/20208472스크립트: 18. Powershell에서는 cmd.exe의 명령어를 지원하진 않습니다.
12204정성태4/1/20208240스크립트: 17. Powershell 명령어에 ';' (semi-colon) 문자가 포함된 경우
12203정성태3/18/202010245오류 유형: 612. warning: 'C:\ProgramData/Git/config' has a dubious owner: '...'.
12202정성태3/18/202012867개발 환경 구성: 486. .NET Framework 프로젝트를 위한 GitLab CI/CD Runner 구성
12201정성태3/18/202010677오류 유형: 611. git-credential-manager.exe: Using credentials for username "Personal Access Token". [1]
12200정성태3/18/202011127VS.NET IDE: 145. NuGet + Github 라이브러리 디버깅 관련 옵션 3가지 - "Enable Just My Code" / "Enable Source Link support" / "Suppress JIT optimization on module load (Managed only)"
12199정성태3/17/20208974오류 유형: 610. C# - CodeDomProvider 사용 시 Unhandled Exception: System.IO.DirectoryNotFoundException: Could not find a part of the path '...\f2_6uod0.tmp'.
12198정성태3/17/202011673오류 유형: 609. SQL 서버 접속 시 "Cannot open user default database. Login failed."
12197정성태3/17/202010819VS.NET IDE: 144. .NET Core 콘솔 응용 프로그램을 배포(publish) 시 docker image 자동 생성 - 두 번째 이야기 [1]
12196정성태3/17/20208775오류 유형: 608. The ServicedComponent being invoked is not correctly configured (Use regsvcs to re-register).
... 46  47  48  49  50  51  52  53  54  55  [56]  57  58  59  60  ...