Microsoft MVP성태의 닷넷 이야기
닷넷: 2197. C# - ClientWebSocket의 Ping, Pong 처리 [링크 복사], [링크+제목 복사],
조회: 10581
글쓴 사람
정성태 (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# - ClientWebSocket의 Ping, Pong 처리

지난 글에 WebSocket의 기본 구현을 다뤄봤는데요,

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

이번에는 Ping/Pong이 어떻게 ClientWebSocket에 구현되었는지 살펴보겠습니다. 이를 위해 그에 앞서 우선 닷넷 WebSocket의 구조를 먼저 살펴볼 필요가 있습니다. 왜냐하면 WebSocket을 상속한 ClientWebSocket은,

System.Net.WebSockets.ClientWebSocket ws = new System.Net.WebSockets.ClientWebSocket();

최소한의 API만 노출하고 있는, 사실상 껍데기에 불과하기 때문입니다. 실질적인 작업은, 이후 ConnectAsync 시점에 불리는,

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

WebSocketHandle 인스턴스가 담당합니다.

// ClientWebSocket 타입

public Task ConnectAsync(Uri uri, HttpMessageInvoker? invoker, CancellationToken cancellationToken)
{
    // ...[생략]...
    return ConnectAsyncCore(uri, invoker, cancellationToken);
}

private async Task ConnectAsyncCore(Uri uri, HttpMessageInvoker? invoker, CancellationToken cancellationToken)
{
    _innerWebSocket = new WebSocketHandle();

    await _innerWebSocket.ConnectAsync(uri, invoker, cancellationToken, Options).ConfigureAwait(false);
   
    // ...[생략]...
}

또한 WebSocketHandle 타입은 내부적으로 WebSocket 필드를 하나 가지고 있는데요, 그곳에는 ConnectAsync 시점에 ManagedWebSocket 인스턴스를 생성해 담아두게 됩니다.

// WebSocketHandle 타입

public async Task ConnectAsync(Uri uri, HttpMessageInvoker? invoker, CancellationToken cancellationToken, ClientWebSocketOptions options)
{
    // ...[생략]...
    WebSocket = WebSocket.CreateFromStream(connectedStream, new WebSocketCreationOptions
    {
        IsServer = false,
        SubProtocol = subprotocol,
        KeepAliveInterval = options.KeepAliveInterval,
        DangerousDeflateOptions = negotiatedDeflateOptions
    });
    // ...[생략]...
}

// WebSocket 타입

public static WebSocket CreateFromStream(Stream stream, WebSocketCreationOptions options)
{
    // ...[생략]...
    return new ManagedWebSocket(stream, options);
}

그러니까, WebSocket 프로토콜과 관련된 기능들은 모두 ManagedWebSocket에서 구현하고 있는 것입니다.




닷넷 ClientWebSocket의 경우, Ping/Pong 처리를 Options.KeepAliveInterval 속성으로 지정할 수 있습니다.

System.Net.WebSockets.ClientWebSocket ws = new System.Net.WebSockets.ClientWebSocket();
ws.Options.KeepAliveInterval = TimeSpan.FromSeconds(10); // 10초마다 서버로 Pong 전송

이후, ManagedWebSocket 내부에서는 SendKeepAliveFrameAsync 메서드가 KeepAliveInterval마다 호출이 되는데요,

// ManagedWebSocket 타입

private void SendKeepAliveFrameAsync()
{
    // This exists purely to keep the connection alive; don't wait for the result, and ignore any failures.
    // The call will handle releasing the lock.  We send a pong rather than ping, since it's allowed by
    // the RFC as a unidirectional heartbeat and we're not interested in waiting for a response.
    ValueTask t = SendFrameAsync(MessageOpcode.Pong, endOfMessage: true, disableCompression: true, ReadOnlyMemory<byte>.Empty, CancellationToken.None);

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

재미있는 건, 이때 Ping이 아닌 Pong을 보낸다는 점입니다. 그 이유는 위의 코드에 남겨진 주석에서 설명하고 있습니다. 어차피 WebSocket의 Ping을 송신해도 서버로부터 응답이 오는 것에 관심이 없으므로, 그냥 클라이언트가 살아 있다는 Pong을 주기적으로 전송하는 역할만 하는 것입니다.

저렇게 (KeepAliveInterval로 인해) 자동 송신되는 Pong을 nodejs에서는 다음과 같이 수신할 수 있습니다.

sockserver.on('connection', ws => {
    console.log('New client connected!')

    ws.send('connection established')

    ws.on('pong', () => console.log('pong received from client!'))

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

따라서, nodejs 서버/닷넷 클라이언트를 실행하면 10초마다 닷넷 클라이언트에서 Pong을 주기적으로 송신하고, nodejs는 ws.on('pong', ...) 코드로 인해 10초마다 "pong received..." 로그가 찍히게 됩니다.




자, 그럼 반대로 nodejs 측에서 ping 또는 pong을 전송하도록 해볼까요?

우선, ping부터 다음과 같은 코드로 전송해 보겠습니다.

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

    console.log('New client connected!')

    ws.send('connection established')

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

    ws.on('close', () => {
        clearInterval(interval_id);
        console.log('Client has disconnected!');
    });

    ws.on('message', data => {
        sockserver.clients.forEach(client => {
            console.log(`distributing message: ${data}`)
            client.send(`echo ${data}`)
        })
    })

    ws.onerror = function () {
        console.log('websocket error')
    }

    interval_id = setInterval(() => {
        ws.ping();
    }, 1000 * 5);
})

보는 바와 같이, 5초 주기로 ws.ping을 호출하고 있고, ws.on('pong', ...)으로 (ping을 보낸 측에서 응답할) pong 수신을 처리하고 있습니다. 닷넷 클라이언트 측은, 이에 대해 KeepAliveInterval을 사용할 필요도 없이 오직 해야 할 일은 "ReceiveAsync" 메서드를 호출해 두는 것입니다.

static async Task Main(string[] args)
{
    string url = "ws://localhost:18000/";

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

    System.Net.WebSockets.ClientWebSocket ws = new System.Net.WebSockets.ClientWebSocket();

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

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

    Console.WriteLine($"Received: {await Read(ws)}");
    await ws.SendAsync(Encoding.UTF8.GetBytes("Hello"), WebSocketMessageType.Text, true, CancellationToken.None);
    Console.WriteLine($"Received: {await Read(ws)}");

    // 위의 코드까지는 Send/Receive 쌍을 맞춰 호출

    // 아래의 코드는 일방적으로 Receive를 하는 경우로 가정
    var result = await ws.ReceiveAsync(new ArraySegment<byte>(new byte[1024]), CancellationToken.None);
    if (result.MessageType == WebSocketMessageType.Close)
    {
        await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None);
        Console.WriteLine("Received close message");
    }

    Console.WriteLine(result.MessageType);
}

이후 nodejs 서버와 닷넷 클라이언트를 실행하면, nodejs 측의 주기적인 ping 신호에 대해 닷넷 클라이언트는 위의 코드상으로는 딱히 반응은 없지만 nodejs 측의 ws.on('pong', ...) 코드가 실행되는 것을 확인할 수 있습니다.




자, 그럼 왜 저렇게 동작하는지 한번 파악해 볼까요? ^^ 위에서 마지막에 호출한 ReceiveAsync 내에서는 nodejs로부터 수신한 Ping 신호를 자동으로 처리하는 코드를 담고 있습니다. 우선, ReceiveAsyncPrivate에서는 다음과 같이 Ping/Pong 신호를 구분해 내고,

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

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

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

        // ...[생략]...
        if (header.Opcode == MessageOpcode.Ping || header.Opcode == MessageOpcode.Pong)
        {
            await HandleReceivedPingPongAsync(header, cancellationToken).ConfigureAwait(false);
            continue;
        }

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

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

private string? TryParseMessageHeaderFromReceiveBuffer(out MessageHeader resultHeader)
{
    // ...[생략]...
    Span<byte> receiveBufferSpan = _receiveBuffer.Span;

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

    header.Opcode = (MessageOpcode)(receiveBufferSpan[_receiveBufferOffset] & 0xF);

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

    // Do basic validation of the header
    switch (header.Opcode)
    {
        // ...[생략]...
        case MessageOpcode.Ping:
        case MessageOpcode.Pong:
            if (header.PayloadLength > MaxControlPayloadLength || !header.Fin)
            {
                // Invalid control messgae
                resultHeader = default;
                return SR.net_Websockets_InvalidControlMessage;
            }
            break;

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

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

Pong 신호인 경우에는 무시하지만, Ping 신호인 경우에는 응답으로 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);
    }

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

비록 ManagedWebSocket 자신은 KeepAliveInterval에 대해 Pong 전송만 하는 형식이었지만, 서버의 ping 신호에 대해서는 약속에 따라 Pong으로 응답하고 있는 것입니다. 따라서 만약 nodejs 측의 ping을 pong으로 바꾸면,

sockserver.on('connection', ws => {
    // ..[생략]...
    ws.on('pong', () => {
        console.log('log after pong'); // 이 코드가 실행되지 않음
    });

    // ..[생략]...

    interval_id = setInterval(() => {
        ws.pong(); // pong을 송신하므로 닷넷 클라이언트는 무응답!
    }, 1000 * 5);
})

ManagedWebSocket의 ReceiveAsyncPrivate 메서드에서는 Pong 수신을 무시하므로 nodejs의 ws.on('pong', ...) 코드도 (ping을 보냈던 것과는 달리) 더 이상 실행되지 않게 됩니다.




위의 소스코드를 정리해 보면, C#의 ClientWebSocket 자체는 Timeout 기능이 없다는 점입니다. 즉, (ReceiveAsync 내부적으로) Ping/Pong을 수신했다고 해서 어떠한 시간을 늘리거나 하는 등의 코드는 전혀 없습니다. 또한 ClientWebSocket은 그 패킷을 받았다는 것을 인지하기 위한 이벤트 핸들러같은 것도 제공하지 않습니다. 게다가 KeepAliveInterval조차도 단지 서버에 내가 살아 있으니 끊지 말라는 식으로 Pong 응답을 주기적으로 보내는 것에 불과하고!

그렇다면 왜 이런 식으로 만든 것일까요?

제가 아직 WebSocket에 대해서는 자세하게 몰라서 확신할 수는 없지만, 어쩌면 이것은 Client의 자원 부담이 상대적으로 Server보다는 덜하다는 점에서 나온 특징인 듯합니다. 즉, Client는 굳이 (WebSocket 수준에서의) Timeout 기능이 없어도 문제 될 가능성이 크지 않지만, Server는 필요 없는 연결 자원에 대해 가능한 빠르게 끊는 것이 더 바람직하기 때문입니다.

물론 Socket 자체의 Timeout 기능도 있고 WebSocket 역시 Send/Receive에서의 연결 해제 감지가 되므로 Client 입장에서 Ping/Pong을 이용한 timeout 체크가 간절하지 않기도 합니다.

반면 서버는, 응용 프로그램 측에서의 프로토콜 결정에 따라 좀 더 공격적으로 연결 여부를 확인하기 위해 필요한 수단이지 않을까 싶습니다. ^^ (혹시 이에 대해 자세한 이력을 아시는 분은 덧글 부탁드립니다.)




다시 간단하게 정리해 보면, 2가지만 기억하면 됩니다.

  1. ClientWebSocket은 KeepAliveInterval을 설정한 경우 서버로 Pong만 전송
  2. 서버로부터 Ping을 수신하면 Pong 응답, 반면 Pong을 수신하면 응답 없음




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

[연관 글]






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

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 136  137  138  139  140  141  142  143  144  145  146  147  148  [149]  150  ...
NoWriterDateCnt.TitleFile(s)
1328정성태8/20/201233286개발 환경 구성: 163. IIS 7 - "MIME Types" 설정 아이콘이 없는 경우
1327정성태8/19/201238021Windows: 58. Windows 8 정식 버전을 설치해 보고... [14]
1326정성태8/19/201224334오류 유형: 160. Visual Studio 2010 Team Explorer 설치 오류
1325정성태8/15/201224354개발 환경 구성: 162. 닷넷 개발자가 컴파일해 본 리눅스
1324정성태8/15/201226379.NET Framework: 332. 함수형 언어의 코드가 그렇게 빠를까? [4]파일 다운로드1
1323정성태8/4/201228160.NET Framework: 331. C# - 클래스 안에 구조체를 포함하는 경우 발생하는 dynamic 키워드의 부작용 [2]
1322정성태8/3/201227795개발 환경 구성: 161. Ubuntu 리눅스의 Hyper-V 지원 (마우스, 네트워크)
1321정성태7/31/201227070개발 환경 구성: 160. Azure - Virtual Machine의 VHD 파일 다운로드 [2]
1320정성태7/30/201229075Math: 10. C# - (타)원 영역의 마우스 클릭 판단파일 다운로드1
1319정성태7/26/201227596개발 환경 구성: 159. Azure - 네트워크 포트 여는 방법 [1]
1317정성태7/24/201226460오류 유형: 159. SpeechRecognitionEngine.SetInputToDefaultAudioDevice 호출 시 System.InvalidOperationException 예외 발생
1316정성태7/18/201284571개발 환경 구성: 158. .NET 응용 프로그램에서 Oracle XE 11g 사용
1315정성태7/17/201229370개발 환경 구성: 157. Azure - Virtual Machine 구성 [2]
1314정성태7/16/201224404개발 환경 구성: 156. Azure - 2개 이상의 서비스 계정을 가지고 있을 때 프로젝트를 배포하는 방법
1313정성태7/16/201236555오류 유형: 158. Hyper-V 설치 후 VM 시작이 안되는 경우
1312정성태7/15/201236433Math: 9. 황금비율 증명
1311정성태7/15/201229134Math: 8. C# - 피보나치 수열의 사각형과 황금 나선(Golden spiral) 그리기파일 다운로드1
1310정성태7/13/201232564Math: 7. C# - 펜타그램(Pentagram) 그리기파일 다운로드1
1309정성태7/13/201230653개발 환경 구성: 155. 윈도우 운영체제에서 기본적으로 사용할 수 있는 압축 해제 방법
1308정성태7/3/201226036.NET Framework: 330. IEnumerator는 언제나 읽기 전용일까?파일 다운로드1
1307정성태6/30/201228288개발 환경 구성: 154. Sysnet, Azure를 만나다. [5]
1306정성태6/29/201228874제니퍼 .NET: 22. 눈으로 확인하는 connectionManagement의 maxconnection 설정값 [4]
1305정성태6/28/201227054오류 유형: 157. IIS 6 - WCF svc 호출 시 404 Not Found 발생
1304정성태6/27/201227810개발 환경 구성: 153. sysnet 첨부 파일을 Azure Storage에 마이그레이션 [3]파일 다운로드1
1303정성태6/26/201227312개발 환경 구성: 152. sysnet DB를 SQL Azure 데이터베이스로 마이그레이션
1302정성태6/25/201229317개발 환경 구성: 151. Azure 웹 사이트에 사용자 도메인 네임 연결하는 방법
... 136  137  138  139  140  141  142  143  144  145  146  147  148  [149]  150  ...