Microsoft MVP성태의 닷넷 이야기
닷넷: 2198. C# - Reflection을 이용한 ClientWebSocket의 Ping 호출 [링크 복사], [링크+제목 복사],
조회: 2135
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)
(시리즈 글이 4개 있습니다.)
닷넷: 2188. C# - ASP.NET Core SignalR로 구현하는 채팅 서비스 예제
; https://www.sysnet.pe.kr/2/0/13504

닷넷: 2189. C# - WebSocket 클라이언트를 닷넷으로 구현하는 예제 (System.Net.WebSockets)
; https://www.sysnet.pe.kr/2/0/13505

닷넷: 2197. C# - ClientWebSocket의 Ping, Pong 처리
; https://www.sysnet.pe.kr/2/0/13518

닷넷: 2198. C# - Reflection을 이용한 ClientWebSocket의 Ping 호출
; https://www.sysnet.pe.kr/2/0/13519




C# - Reflection을 이용한 ClientWebSocket의 Ping 호출

지난 글에 Ping/Pong이 ClientWebSocket에 의해 어떻게 처리되는지 살펴봤습니다.

C# - ClientWebSocket의 Ping, Pong 처리
; https://www.sysnet.pe.kr/2/0/13518

언급했듯이, (서버 측 nodejs는 Ping을 전송하고 Pong을 받는데) C#의 ClientWebSocket은 무조건 Pong을 전송하는 식입니다. 그렇다면 혹시 Ping을 전송하는 방법은 없을까요?

이미 설명한 것처럼, 모든 처리는 ManagedWebSocket 내부에서 자동으로 수행되는데다 ClientWebSocket이 호출하는 Send 메서드는 내부적으로 Binary와 Text 유형만 보낼 수 있도록 고정했기 때문에,

public override ValueTask SendAsync(ReadOnlyMemory<byte> buffer, WebSocketMessageType messageType, WebSocketMessageFlags messageFlags, CancellationToken cancellationToken)
{
    // ...[생략]...
    MessageOpcode opcode;

    if (_lastSendWasFragment)
    {
        if (_lastSendHadDisableCompression != disableCompression)
        {
            throw new ArgumentException(SR.net_WebSockets_Argument_MessageFlagsHasDifferentCompressionOptions, nameof(messageFlags));
        }
        opcode = MessageOpcode.Continuation;
    }
    else
    {
        opcode = messageType == WebSocketMessageType.Binary ? MessageOpcode.Binary : MessageOpcode.Text;
    }

    ValueTask t = SendFrameAsync(opcode, endOfMessage, disableCompression, buffer, cancellationToken);
    // ...[생략]...

    return t;
}

딱히 제어를 할 수 있는 여지가 없습니다. 정 원한다면, 가령 테스트를 위해서 필요하다면 Reflection을 이용해 처리하는 수밖에 없습니다.

그다지 어렵지 않으니 간단하게 코드로 만들어 볼까요? ^^ 우선 SocketHandle과 ManagedWebSocket을 차례로 구하는 것부터 시작해야 합니다.

private static object? GetSocketHandle(ClientWebSocket ws)
{
    Type type = ws.GetType();
    FieldInfo? fi = type.GetField("_innerWebSocket", BindingFlags.NonPublic | BindingFlags.Instance);
    if (fi == null)
    {
        return null;
    }

    return fi.GetValue(ws);
}

private static WebSocket? GetManagedSocket(ClientWebSocket ws)
{
    var webSocketHandle = GetSocketHandle(ws);
    if (webSocketHandle == null)
    {
        return null;
    }

    Type type = webSocketHandle.GetType();
    return type.GetProperty("WebSocket", BindingFlags.Public | BindingFlags.Instance)?.GetValue(webSocketHandle)
        as WebSocket;
}

이후 남은 작업은, ManagedWebSocket이 구현한 Pong 코드를 참조해,

private async ValueTask HandleReceivedPingPongAsync(MessageHeader header, CancellationToken cancellationToken)
{
    // ...[생략]...

    // If this was a ping, send back a pong response.
    if (header.Opcode == MessageOpcode.Ping)
    {
        // ...[생략]...
        await SendFrameAsync(
            MessageOpcode.Pong,)
            endOfMessage: true,
            disableCompression: true,
            _receiveBuffer.Slice(_receiveBufferOffset, (int)header.PayloadLength),
            cancellationToken).ConfigureAwait(false);
    }

    // ...[생략]...
}

우리도 저 SendFrameAsync 메서드를 이용해 MessageOpcode.Ping (0x9)에 해당하는 값을 전송하도록 맞춰주기만 하면 됩니다.

private static ValueTask SendPingFrameAsync(WebSocket managedSocket)
{
    Type type = managedSocket.GetType();
    MethodInfo? targetMi = null;

    foreach (MethodInfo mi in type.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance))
    {
        if (mi.Name == "SendFrameAsync" && mi.GetParameters().Length == 5)
        {
            targetMi = mi;
            break;
        }
    }

    if (targetMi == null)
    {
        throw new NullReferenceException("SendFrameAsync not found");
    }

    /*
    private enum MessageOpcode : byte
    {
        Continuation = 0x0,
        Text = 0x1,
        Binary = 0x2,
        Close = 0x8,
        Ping = 0x9,
        Pong = 0xA
    }
    */

    object? objValue = targetMi.Invoke(managedSocket, new object?[] { (byte)0x9, true, true, ReadOnlyMemory<byte>.Empty, CancellationToken.None });
    if (objValue == null)
    {
        throw new NullReferenceException("SendFrameAsync returned null");
    }

    return (ValueTask)objValue;
}

private static void SendKeepAliveFrame(WebSocket managedSocket)
{
    ValueTask t = SendPingFrameAsync(managedSocket);
    if (t.IsCompletedSuccessfully)
    {
        t.GetAwaiter().GetResult();
    }
    else
    {
        // "Observe" any exception, ignoring it to prevent the unobserved exception event from being raised.
        t.AsTask().ContinueWith(static p => { _ = p.Exception; },
            CancellationToken.None,
            TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously,
            TaskScheduler.Default);
    }
}

끝이군요. ^^ 이제 위에서 구현한 SendKeepAliveFrame 메서드를 ClientWebSocket에 적용해 다음과 같이 일부러 Ping을 전송하는 코드를 만들 수 있습니다.

string url = "ws://localhost:18000/";

var connectTimeout = new CancellationTokenSource();
connectTimeout.CancelAfter(2000);

System.Net.WebSockets.ClientWebSocket ws = new System.Net.WebSockets.ClientWebSocket();
ws.Options.KeepAliveInterval = TimeSpan.FromSeconds(0); // Pong 전송 코드 수행을 막기 위해 일부러 0으로 설정

await ws.ConnectAsync(new Uri(url), connectTimeout.Token);

if (ws.State != System.Net.WebSockets.WebSocketState.Open)
{
    Console.WriteLine($"Failed to connect: {url}");
    return;
}

_ = Task.Run(() =>
{
    WebSocket? managedSocket = GetManagedSocket(ws);
    if (managedSocket == null)
    {
        return;
    }

    while (true)
    {
        SendKeepAliveFrame(managedSocket);
        Thread.Sleep(5000);
    }
});

끝입니다. 잘 동작하는지 확인을 위해 nodejs 서버 코드에 로그를 남겨 보면,

var { WebSocketServer } = require('ws')

const sockserver = new WebSocketServer({ port: 18000 })

sockserver.on('connection', ws => {
    interval_id = 0;

    console.log('New client connected!')

    ws.send('connection established')

    ws.on('ping', () => {
        console.log('ping received from client');
    });

    // ...[생략]...
})

정상적으로 "ping received ..." 메시지가 출력되는 것을 볼 수 있습니다. 당연히 nodejs는 저렇게 ping을 수신하면 응답으로 pong을 다시 클라이언트로 전송하게 될 것입니다. 아쉽게도 수신 여부를 ClientWebSocket으로 알 수는 없지만, 비주얼 스튜디오의 닷넷 소스코드 디버깅 기능을 이용하면,

비주얼 스튜디오 2022를 이용한 (소스 코드가 없는) 닷넷 모듈 디버깅 - "외부 원본(External Sources)"
; https://www.sysnet.pe.kr/2/0/13109

ReceiveAsyncPrivate 메서드 내부의 MessageOpcode.Pong 조건절에 BP를 설정해 확인해 볼 수는 있습니다.

[AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder<>))]
private async ValueTask ReceiveAsyncPrivate(Memory payloadBuffer, CancellationToken cancellationToken)
{
    // ...[생략]...

    while (true) // in case we get control frames that should be ignored from the user's perspective
    {
        // ...[생략]...
        await _stream.ReadAsync(Memory.Empty, cancellationToken).ConfigureAwait(false);

        // ...[생략]...
        string? headerErrorMessage = TryParseMessageHeaderFromReceiveBuffer(out header);

        // 아래의 코드에 Breakpoint 설정
        if (header.Opcode == MessageOpcode.Ping || header.Opcode == MessageOpcode.Pong)
        {
            await HandleReceivedPingPongAsync(header, cancellationToken).ConfigureAwait(false);
            continue;
        }

        // ...[생략]...
    }

    // ...[생략]...
}

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 1/10/2024]

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)
13516정성태1/7/20242344닷넷: 2196. IIS - AppPool의 "Disable Overlapped Recycle" 옵션의 부작용
13515정성태1/6/20242621닷넷: 2195. async 메서드 내에서 C# 7의 discard 구문 활용 사례 [1]
13514정성태1/5/20242308개발 환경 구성: 702. IIS - AppPool의 "Disable Overlapped Recycle" 옵션
13513정성태1/5/20242224닷넷: 2194. C# - WebActivatorEx / System.Web의 PreApplicationStartMethod 특성
13512정성태1/4/20242176개발 환경 구성: 701. IIS - w3wp.exe 프로세스의 ASP.NET 런타임을 항상 Warmup 모드로 유지하는 preload Enabled 설정
13511정성태1/4/20242198닷넷: 2193. C# - ASP.NET Web Application + OpenAPI(Swashbuckle) 스펙 제공
13510정성태1/3/20242120닷넷: 2192. C# - 특정 실행 파일이 있는지 확인하는 방법 (Linux)
13509정성태1/3/20242169오류 유형: 887. .NET Core 2 이하의 프로젝트에서 System.Runtime.CompilerServices.Unsafe doesn't support netcoreapp2.0.
13508정성태1/3/20242221오류 유형: 886. ORA-28000: the account is locked
13507정성태1/2/20242871닷넷: 2191. C# - IPGlobalProperties를 이용해 netstat처럼 사용 중인 Socket 목록 구하는 방법파일 다운로드1
13506정성태12/29/20232461닷넷: 2190. C# - 닷넷 코어/5+에서 달라지는 System.Text.Encoding 지원
13505정성태12/27/20232990닷넷: 2189. C# - WebSocket 클라이언트를 닷넷으로 구현하는 예제 (System.Net.WebSockets)파일 다운로드1
13504정성태12/27/20232579닷넷: 2188. C# - ASP.NET Core SignalR로 구현하는 채팅 서비스 예제파일 다운로드1
13503정성태12/27/20232443Linux: 67. WSL 환경 + mlocate(locate) 도구의 /mnt 디렉터리 검색 문제
13502정성태12/26/20232565닷넷: 2187. C# - 다른 프로세스의 환경변수 읽는 예제파일 다운로드1
13501정성태12/25/20232325개발 환경 구성: 700. WSL + uwsgi - IPv6로 바인딩하는 방법
13500정성태12/24/20232416디버깅 기술: 194. Windbg - x64 가상 주소를 물리 주소로 변환
13498정성태12/23/20233102닷넷: 2186. 한국투자증권 KIS Developers OpenAPI의 C# 래퍼 버전 - eFriendOpenAPI NuGet 패키지
13497정성태12/22/20232496오류 유형: 885. Visual Studiio - error : Could not connect to the remote system. Please verify your connection settings, and that your machine is on the network and reachable.
13496정성태12/21/20232490Linux: 66. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (gdb)
13495정성태12/20/20232417Linux: 65. clang++로 공유 라이브러리의 -static 옵션 빌드가 가능할까요?
13494정성태12/20/20232591Linux: 64. Linux 응용 프로그램의 (C++) so 의존성 줄이기(ReleaseMinDependency) - 두 번째 이야기
13493정성태12/19/20232722닷넷: 2185. C# - object를 QueryString으로 직렬화하는 방법
13492정성태12/19/20232394개발 환경 구성: 699. WSL에 nopCommerce 예제 구성
13491정성태12/19/20232269Linux: 63. 리눅스 - 다중 그룹 또는 사용자를 리소스에 권한 부여
13490정성태12/19/20232399개발 환경 구성: 698. Golang - GLIBC 의존을 없애는 정적 빌드 방법
1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...