Microsoft MVP성태의 닷넷 이야기
.NET Framework: 594. C# - WCF wsDualHttpBinding의 ClientBaseAddress 속성 [링크 복사], [링크+제목 복사]
조회: 15535
글쓴 사람
정성태 (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)
13484정성태12/14/20232176개발 환경 구성: 694. Windows 디렉터리 경로를 WSL의 /mnt 포맷으로 구하는 방법
13483정성태12/14/20232317닷넷: 2184. C# - 하나의 resource 파일을 여러 프로그램에서 (AOT 시에도) 사용하는 방법파일 다운로드1
13482정성태12/13/20232917닷넷: 2183. C# - eFriend Expert OCX 예제를 .NET Core/5+ Console App에서 사용하는 방법 [2]파일 다운로드1
13481정성태12/13/20232293개발 환경 구성: 693. msbuild - .NET Core/5+ 프로젝트에서 resgen을 이용한 리소스 파일 생성 방법파일 다운로드1
13480정성태12/12/20232664개발 환경 구성: 692. Windows WSL 2 + Chrome 웹 브라우저 설치
13479정성태12/11/20232347개발 환경 구성: 691. WSL 2 (Ubuntu) + nginx 환경 설정
13477정성태12/8/20232540닷넷: 2182. C# - .NET 7부터 추가된 Int128, UInt128 [1]파일 다운로드1
13476정성태12/8/20232274닷넷: 2181. C# - .NET 8 JsonStringEnumConverter의 AOT를 위한 개선파일 다운로드1
13475정성태12/7/20232343닷넷: 2180. .NET 8 - 함수 포인터에 대한 Reflection 정보 조회파일 다운로드1
13474정성태12/6/20232185개발 환경 구성: 690. 닷넷 코어/5+ 버전의 ilasm/ildasm 실행 파일 구하는 방법 - 두 번째 이야기
13473정성태12/5/20232396닷넷: 2179. C# - 값 형식(Blittable)을 메모리 복사를 이용해 바이트 배열로 직렬화/역직렬화파일 다운로드1
13472정성태12/4/20232218C/C++: 164. Visual C++ - InterlockedCompareExchange128 사용 방법
13471정성태12/4/20232295Copilot - To enable GitHub Copilot, authorize this extension using GitHub's device flow
13470정성태12/2/20232597닷넷: 2178. C# - .NET 8부터 COM Interop에 대한 자동 소스 코드 생성 도입파일 다운로드1
13469정성태12/1/20232318닷넷: 2177. C# - (Interop DLL 없이) CoClass를 이용한 COM 개체 생성 방법파일 다운로드1
13468정성태12/1/20232258닷넷: 2176. C# - .NET Core/5+부터 달라진 RCW(Runtime Callable Wrapper) 대응 방식파일 다운로드1
13467정성태11/30/20232354오류 유형: 882. C# - Unhandled exception. System.Runtime.InteropServices.COMException (0x800080A5)파일 다운로드1
13466정성태11/29/20232521닷넷: 2175. C# - DllImport 메서드의 AOT 지원을 위한 LibraryImport 옵션
13465정성태11/28/20232294개발 환경 구성: 689. MSBuild - CopyToOutputDirectory가 "dotnet publish" 시에는 적용되지 않는 문제파일 다운로드1
13464정성태11/28/20232421닷넷: 2174. C# - .NET 7부터 UnmanagedCallersOnly 함수 export 기능을 AOT 빌드에 통합파일 다운로드1
13463정성태11/27/20232379오류 유형: 881. Visual Studio - NU1605: Warning As Error: Detected package downgrade
13462정성태11/27/20232393오류 유형: 880. Visual Studio - error CS0246: The type or namespace name '...' could not be found
13461정성태11/26/20232416닷넷: 2173. .NET Core 3/5+ 기반의 COM Server를 registry 등록 없이 사용하는 방법파일 다운로드1
13460정성태11/26/20232365닷넷: 2172. .NET 6+ 기반의 COM Server 내에 Type Library를 내장하는 방법파일 다운로드1
13459정성태11/26/20232334닷넷: 2171. .NET Core 3/5+ 기반의 COM Server를 기존의 regasm처럼 등록하는 방법파일 다운로드1
13458정성태11/26/20232359닷넷: 2170. .NET Core/5+ 기반의 COM Server를 tlb 파일을 생성하는 방법(tlbexp)
1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...