Microsoft MVP성태의 닷넷 이야기
.NET Framework: 594. C# - WCF wsDualHttpBinding의 ClientBaseAddress 속성 [링크 복사], [링크+제목 복사]
조회: 15482
글쓴 사람
정성태 (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)
12348정성태9/25/20209597오류 유형: 658. 리눅스 docker - Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock
12347정성태9/25/202023722Windows: 174. WSL 2의 네트워크 통신 방법 [4]
12346정성태9/25/20208843오류 유형: 657. IIS - http://localhost 방문 시 Service Unavailable 503 오류 발생
12345정성태9/25/20208555오류 유형: 656. iisreset 실행 시 "Restart attempt failed." 오류가 발생하지만 웹 서비스는 정상적인 경우파일 다운로드1
12344정성태9/25/20209729Windows: 173. 서비스 관리자에 "IIS Admin Service"가 등록되어 있지 않다면?
12343정성태9/24/202019235.NET Framework: 945. C# - 닷넷 응용 프로그램에서 메모리 누수가 발생할 수 있는 패턴 [5]
12342정성태9/24/202010583디버깅 기술: 171. windbg - 인스턴스가 살아 있어 메모리 누수가 발생하고 있는지 확인하는 방법
12341정성태9/23/20209745.NET Framework: 944. C# - 인스턴스가 살아 있어 메모리 누수가 발생하고 있는지 확인하는 방법파일 다운로드1
12340정성태9/23/20209483.NET Framework: 943. WPF - WindowsFormsHost를 담은 윈도우 생성 시 메모리 누수
12339정성태9/21/20209464오류 유형: 655. 코어 모드의 윈도우는 GUI 모드의 윈도우로 교체가 안 됩니다.
12338정성태9/21/20208981오류 유형: 654. 우분투 설치 시 "CHS: Error 2001 reading sector ..." 오류 발생
12337정성태9/21/202010278오류 유형: 653. Windows - Time zone 설정을 바꿔도 반영이 안 되는 경우
12336정성태9/21/202012782.NET Framework: 942. C# - WOL(Wake On Lan) 구현
12335정성태9/21/202022195Linux: 31. 우분투 20.04 초기 설정 - 고정 IP 및 SSH 설치
12334정성태9/21/20207647오류 유형: 652. windbg - !py 확장 명령어 실행 시 "failed to find python interpreter"
12333정성태9/20/20208088.NET Framework: 941. C# - 전위/후위 증감 연산자에 대한 오버로딩 구현 (2)
12332정성태9/18/202010096.NET Framework: 940. C# - Windows Forms ListView와 DataGridView의 예제 코드파일 다운로드1
12331정성태9/18/20209286오류 유형: 651. repadmin /syncall - 0x80090322 The target principal name is incorrect.
12330정성태9/18/202010309.NET Framework: 939. C# - 전위/후위 증감 연산자에 대한 오버로딩 구현 [2]파일 다운로드1
12329정성태9/16/202012239오류 유형: 650. ASUS 메인보드 관련 소프트웨어 설치 후 ArmouryCrate.UserSessionHelper.exe 프로세스 무한 종료 현상
12328정성태9/16/202012419VS.NET IDE: 150. TFS의 이력에서 "Get This Version"과 같은 기능을 Git으로 처리한다면?
12327정성태9/12/202010029.NET Framework: 938. C# - ICS(Internet Connection Sharing) 제어파일 다운로드1
12326정성태9/12/20209554개발 환경 구성: 516. Azure VM의 Network Adapter를 실수로 비활성화한 경우
12325정성태9/12/20209104개발 환경 구성: 515. OpenVPN - 재부팅 후 ICS(Internet Connection Sharing) 기능이 동작 안하는 문제
12324정성태9/11/202010334개발 환경 구성: 514. smigdeploy.exe를 이용한 Windows Server 2016에서 2019로 마이그레이션 방법
12323정성태9/11/20209265오류 유형: 649. Copy Database Wizard - The job failed. Check the event log on the destination server for details.
... 46  47  48  49  50  [51]  52  53  54  55  56  57  58  59  60  ...