Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (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# - WebSocket 클라이언트를 닷넷으로 구현하는 예제 (System.Net.WebSockets)

지난 글에서,

C# - ASP.NET Core SignalR로 구현하는 채팅 서비스 예제
; https://www.sysnet.pe.kr/2/0/13504

SignalR로 채팅 서비스를 구현하면서 대충 WebSocket에 대한 맛보기를 했으니 어떤 기술인지 감은 잡았을 것입니다. 물론 SignalR 서비스가 구현이 매우 용이해서 좋긴 한데, 때로는 기존의 nodejs 등으로 구현한 WebSocket과 통신할 경우도 발생할 수 있으니 이에 대해서도 마저 알아보겠습니다.

그런 경우, RFC 문서를 보며 직접 구현하는 것도 가능한데 ^^ 그래도 적절한 WebSocket 클라이언트 라이브러리를 활용하는 것도 좋은 선택입니다. 검색해 보면 Websocket.Client 등도 나오지만,

Your First C# Websocket Client
; https://medium.com/nerd-for-tech/your-first-c-websocket-client-5e7acc30681d

이 글에서는 닷넷 자체에 이미 내장돼 있는 System.Net.WebSockets를 사용해 보겠습니다. 그렇긴 한데, 사실 이것도 다음과 같은 글에서 너무 자세하세 잘 소개하고 있어서,

WebSockets support in ASP.NET Core
; https://learn.microsoft.com/en-us/aspnet/core/fundamentals/websockets

WebSocket in .NET - Real-Time, Two-Way Communication Over TCP/IP
; https://medium.com/@kova98/websockets-in-net-59f1fc69bdcb

C# WebSocket
; https://zetcode.com/csharp/websocket/

저는 그냥 베끼는 수준으로만 정리해 보겠습니다. ^^;




예를 들어, nodejs로 다음과 같은 식의 WebSocket 서버를 만들어 볼까요?

var { WebSocketServer } = require('ws')

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

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

    ws.send('connection established')

    ws.on('close', () => console.log('Client has disconnected!'))

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

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

SignalR 서버를 작성해 봤다면, 구조가 묘하게 닮아 있어 닷넷 개발 경험만 있어도 위의 소스코드가 눈에 잘 들어올 것입니다. 게다가 Socket 서버 경험까지 있다면, socketserver 인스턴스를 서버 소켓으로, 이후 socketserver.on('connection', ws => {...}) 코드의 ws를 Accept로 받은 자식 소켓으로 쉽게 매칭이 될 것입니다.

자, 그럼 위의 소스 코드와 통신하는 WebSocket 클라이언트를 C#으로 다음과 같이 작성할 수 있습니다.

using System.Net.WebSockets;
using System.Text;

namespace WebSocketClient;

internal class Program
{
    static async Task Main(string[] args)
    {
        Console.WriteLine("Press any key to start");
        Console.ReadLine();

        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)}");

        await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None);
    }

    private static async Task<string> Read(ClientWebSocket ws)
    {
        var buffer = new byte[1024];
        var result = await ws.ReceiveAsync(buffer, CancellationToken.None);
        return Encoding.UTF8.GetString(buffer, 0, result.Count);
    }
}

단지 비동기 구문만 살짝 더 곁들여져서 복잡한 듯하지만, 기존의 TCP 소켓과 사용법이 거의 유사해서 딱히 더 설명할 것이 없을 정도군요. ^^;

암튼, 그냥 어렵지 않으니 언제든 쉽게 적용할 수 있다는 정도였다는 것만 알고 넘어가도 되겠습니다.

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




참고로, WebSocket을 아예 TCP Socket 레벨에서 다루고 싶다면 아래의 글이 도움이 될 것입니다.

Writing a WebSocket server in C#
; https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_server

C# WebSocket 서버 구현
; https://hgarchive.tistory.com/4

Golang으로 직접 WebSocket 통신 구현해보기
; https://docs.google.com/document/d/e/2PACX-1vRrf1SD1k4FyXv1G-DPlDbX9F3KsNMnKogF4SrUNqkA9X5P8F-w2yTGzgDunctdpfHIfmoQZaFZ3jm4/pub

거의 RFC 6455 규약대로 구현을 하고 있기 때문에 Web Socket에 대한 이해를 높일 수 있을 것입니다. 엄밀히 말해서, 단순한 TCP 통신의 한 사례일 뿐, 어쩌면 JavaScript가 이런 정도로까지 대중화하지 않았다면 나오지 않았을 기술입니다.




만약 이런 오류가 발생한다면?

System.Net.WebSockets.WebSocketException
  HResult=0x80004005
  Message=Unable to connect to the remote server
  Source=System.Net.WebSockets.Client
  StackTrace:
   at System.Net.WebSockets.WebSocketHandle.<ConnectAsync>d__22.MoveNext() in /_/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.Managed.cs:line 221

  This exception was originally thrown at this call stack:
    System.Net.Security.SslStream.GetFrameSize(System.ReadOnlySpan<byte>) in SslStream.IO.cs
    System.Net.Security.SslStream.EnsureFullTlsFrameAsync<TIOAdapter>(System.Threading.CancellationToken, int) in SslStream.IO.cs
    System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder<TResult>.StateMachineBox<TStateMachine>.System.Threading.Tasks.Sources.IValueTaskSource<TResult>.GetResult(short) in PoolingAsyncValueTaskMethodBuilderT.cs
    System.Net.Security.SslStream.ReceiveHandshakeFrameAsync<TIOAdapter>(System.Threading.CancellationToken) in SslStream.IO.cs
    System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable<TResult>.ConfiguredValueTaskAwaiter.GetResult() in ConfiguredValueTaskAwaitable.cs
    System.Net.Security.SslStream.ForceAuthenticationAsync<TIOAdapter>(bool, byte[], System.Threading.CancellationToken) in SslStream.IO.cs
    System.Net.Security.SslStream.ProcessAuthenticationWithTelemetryAsync(bool, System.Threading.CancellationToken) in SslStream.IO.cs
    System.Net.Http.ConnectHelper.EstablishSslConnectionAsync(System.Net.Security.SslClientAuthenticationOptions, System.Net.Http.HttpRequestMessage, bool, System.IO.Stream, System.Threading.CancellationToken) in ConnectHelper.cs

Inner Exception 1:
HttpRequestException: The SSL connection could not be established, see inner exception.

Inner Exception 2:
AuthenticationException: Cannot determine the frame size or a corrupted frame was received.

SSL 통신으로 열어놓지 않은 WebSocket에 wss 프로토콜로 접근했기 때문입니다.

System.Net.WebSockets.ClientWebSocket ws = new System.Net.WebSockets.ClientWebSocket();
await ws.ConnectAsync(new Uri("wss://localhost:18000/"), CancellationToken.None);

HTTP와 HTTPS의 관계처럼, WS와 WSS는 Secure Socket 통신의 여부를 결정합니다.




이런 오류가 발생한다면?

System.Net.WebSockets.WebSocketException
  HResult=0x80004005
  Message=The server returned status code '200' when status code '101' was expected.
  Source=System.Net.WebSockets.Client
  StackTrace:
   at System.Net.WebSockets.WebSocketHandle.ValidateResponse(HttpResponseMessage response, String secValue) in /_/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.Managed.cs:line 454

접속하려는 WebSocket 주소가 올바른지 확인해 볼 필요가 있습니다. 즉, HTTP 웹 서비스가 반응하는 경우 저런 오류가 발생하게 됩니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 4/5/2024]

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

비밀번호

댓글 작성자
 




... [76]  77  78  79  80  81  82  83  84  85  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
12036정성태10/14/201925523.NET Framework: 866. C# - 고성능이 필요한 환경에서 GC가 발생하지 않는 네이티브 힙 사용파일 다운로드1
12035정성태10/13/201919623개발 환경 구성: 461. C# 8.0의 #nulable 관련 특성을 .NET Framework 프로젝트에서 사용하는 방법 [2]파일 다운로드1
12034정성태10/12/201918961개발 환경 구성: 460. .NET Core 환경에서 (프로젝트가 아닌) C# 코드 파일을 입력으로 컴파일하는 방법 [1]
12033정성태10/11/201923173개발 환경 구성: 459. .NET Framework 프로젝트에서 C# 8.0/9.0 컴파일러를 사용하는 방법
12032정성태10/8/201919286.NET Framework: 865. .NET Core 2.2/3.0 웹 프로젝트를 IIS에서 호스팅(Inproc, out-of-proc)하는 방법 - AspNetCoreModuleV2 소개
12031정성태10/7/201916568오류 유형: 569. Azure Site Extension 업그레이드 시 "System.IO.IOException: There is not enough space on the disk" 예외 발생
12030정성태10/5/201923373.NET Framework: 864. .NET Conf 2019 Korea - "닷넷 17년의 변화 정리 및 닷넷 코어 3.0" 발표 자료 [1]파일 다운로드1
12029정성태9/27/201924216제니퍼 .NET: 29. Jennifersoft provides a trial promotion on its APM solution such as JENNIFER, PHP, and .NET in 2019 and shares the examples of their application.
12028정성태9/26/201919167.NET Framework: 863. C# - Thread.Suspend 호출 시 응용 프로그램 hang 현상을 해결하기 위한 시도파일 다운로드1
12027정성태9/26/201914847오류 유형: 568. Consider app.config remapping of assembly "..." from Version "..." [...] to Version "..." [...] to solve conflict and get rid of warning.
12026정성태9/26/201920253.NET Framework: 862. C# - Active Directory의 LDAP 경로 및 정보 조회
12025정성태9/25/201918580제니퍼 .NET: 28. APM 솔루션 제니퍼, PHP, .NET 무료 사용 프로모션 2019 및 적용 사례 (8) [1]
12024정성태9/20/201920512.NET Framework: 861. HttpClient와 HttpClientHandler의 관계 [2]
12023정성태9/18/201920963.NET Framework: 860. ServicePointManager.DefaultConnectionLimit와 HttpClient의 관계파일 다운로드1
12022정성태9/12/201924908개발 환경 구성: 458. C# 8.0 (Preview) 신규 문법을 위한 개발 환경 구성 [3]
12021정성태9/12/201940715도서: 시작하세요! C# 8.0 프로그래밍 [4]
12020정성태9/11/201923892VC++: 134. SYSTEMTIME 값 기준으로 특정 시간이 지났는지를 판단하는 함수
12019정성태9/11/201917439Linux: 23. .NET Core + 리눅스 환경에서 Environment.CurrentDirectory 접근 시 주의 사항
12018정성태9/11/201916234오류 유형: 567. IIS - Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive. (D:\lowSite4\web.config line 11)
12017정성태9/11/201920050오류 유형: 566. 비주얼 스튜디오 - Failed to register URL "http://localhost:6879/" for site "..." application "/". Error description: Access is denied. (0x80070005)
12016정성태9/5/201920056오류 유형: 565. git fetch - warning: 'C:\ProgramData/Git/config' has a dubious owner: '(unknown)'.
12015정성태9/3/201925475개발 환경 구성: 457. 윈도우 응용 프로그램의 Socket 연결 시 time-out 시간 제어
12014정성태9/3/201919240개발 환경 구성: 456. 명령행에서 AWS, Azure 등의 원격 저장소에 파일 관리하는 방법 - cyberduck/duck 소개
12013정성태8/28/201922132개발 환경 구성: 455. 윈도우에서 (테스트) 인증서 파일 만드는 방법 [3]
12012정성태8/28/201926710.NET Framework: 859. C# - HttpListener를 이용한 HTTPS 통신 방법
12011정성태8/27/201926259사물인터넷: 57. C# - Rapsberry Pi Zero W와 PC 간 Bluetooth 통신 예제 코드파일 다운로드1
... [76]  77  78  79  80  81  82  83  84  85  86  87  88  89  90  ...