성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] 제가 큰 실수를 했군요. ^^; Delegate를 통한 Bein...
[정성태] Working with Rust Libraries from C#...
[정성태] Detecting blocking calls using asyn...
[정성태] 아쉽게도, 커뮤니티는 아니고 개인 블로그입니다. ^^
[정성태] 질문이 잘 이해가 안 됩니다. 우선, 해당 소스코드에서 ILis...
[양승조
] var대신 dinamic으로 선언해서 해결은 했습니다. 맞는 해...
[양승조
] 또 막혔습니다. ㅠㅠ var list = props[i].Ge...
[양승조
] 아. 감사합니다. 어제는 안됐던것 같은데....정신을 차려야겠네...
[정성태] "props[i].GetValue(props[i])" 코드에서 ...
[정성태] 저렇게 조각 코드 말고, 실제로 재현이 되는 예제 프로젝트를 압...
글쓰기
제목
이름
암호
전자우편
HTML
홈페이지
유형
제니퍼 .NET
닷넷
COM 개체 관련
스크립트
VC++
VS.NET IDE
Windows
Team Foundation Server
디버깅 기술
오류 유형
개발 환경 구성
웹
기타
Linux
Java
DDK
Math
Phone
Graphics
사물인터넷
부모글 보이기/감추기
내용
<div style='display: inline'> <h1 style='font-family: Malgun Gothic, Consolas; font-size: 20pt; color: #006699; text-align: center; font-weight: bold'>C# - WebSocket 클라이언트를 닷넷으로 구현하는 예제 (System.Net.WebSockets)</h1> <p> 지난 글에서,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > C# - ASP.NET Core SignalR로 구현하는 채팅 서비스 예제 ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/13504'>https://www.sysnet.pe.kr/2/0/13504</a> </pre> <br /> SignalR로 채팅 서비스를 구현하면서 대충 WebSocket에 대한 맛보기를 했으니 어떤 기술인지 감은 잡았을 것입니다. 물론 SignalR 서비스가 구현이 매우 용이해서 좋긴 한데, 때로는 기존의 nodejs 등으로 구현한 WebSocket과 통신할 경우도 발생할 수 있으니 이에 대해서도 마저 알아보겠습니다.<br /> <br /> 그런 경우, RFC 문서를 보며 직접 구현하는 것도 가능한데 ^^ 그래도 적절한 WebSocket 클라이언트 라이브러리를 활용하는 것도 좋은 선택입니다. 검색해 보면 Websocket.Client 등도 나오지만,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > Your First C# Websocket Client ; <a target='tab' href='https://medium.com/nerd-for-tech/your-first-c-websocket-client-5e7acc30681d'>https://medium.com/nerd-for-tech/your-first-c-websocket-client-5e7acc30681d</a> </pre> <br /> 이 글에서는 닷넷 자체에 이미 내장돼 있는 System.Net.WebSockets를 사용해 보겠습니다. 그렇긴 한데, 사실 이것도 다음과 같은 글에서 너무 자세하세 잘 소개하고 있어서,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > WebSockets support in ASP.NET Core ; <a target='tab' href='https://learn.microsoft.com/en-us/aspnet/core/fundamentals/websockets'>https://learn.microsoft.com/en-us/aspnet/core/fundamentals/websockets</a> WebSocket in .NET - Real-Time, Two-Way Communication Over TCP/IP ; <a target='tab' href='https://medium.com/@kova98/websockets-in-net-59f1fc69bdcb'>https://medium.com/@kova98/websockets-in-net-59f1fc69bdcb</a> C# WebSocket ; <a target='tab' href='https://zetcode.com/csharp/websocket/'>https://zetcode.com/csharp/websocket/</a> </pre> <br /> 저는 그냥 베끼는 수준으로만 정리해 보겠습니다. ^^;<br /> <br /> <hr style='width: 50%' /><br /> <br /> 예를 들어, nodejs로 다음과 같은 식의 WebSocket 서버를 만들어 볼까요?<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > 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') } }) </pre> <br /> SignalR 서버를 작성해 봤다면, 구조가 묘하게 닮아 있어 닷넷 개발 경험만 있어도 위의 소스코드가 눈에 잘 들어올 것입니다. 게다가 Socket 서버 경험까지 있다면, socketserver 인스턴스를 서버 소켓으로, 이후 socketserver.on('connection', ws => {...}) 코드의 ws를 Accept로 받은 자식 소켓으로 쉽게 매칭이 될 것입니다.<br /> <br /> 자, 그럼 위의 소스 코드와 통신하는 WebSocket 클라이언트를 C#으로 다음과 같이 작성할 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > 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); <span style='color: blue; font-weight: bold'>System.Net.WebSockets.ClientWebSocket ws = new System.Net.WebSockets.ClientWebSocket(); await ws.ConnectAsync(new Uri(url), connectTimeout.Token);</span> if (ws.State != System.Net.WebSockets.WebSocketState.Open) { Console.WriteLine($"Failed to connect: {url}"); return; } Console.WriteLine($"Received: {<span style='color: blue; font-weight: bold'>await Read(ws)</span>}"); <span style='color: blue; font-weight: bold'>await ws.SendAsync(Encoding.UTF8.GetBytes("Hello"), WebSocketMessageType.Text, true, CancellationToken.None);</span> Console.WriteLine($"Received: {<span style='color: blue; font-weight: bold'>await Read(ws)</span>}"); <span style='color: blue; font-weight: bold'>await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None);</span> } private static async Task<string> Read(ClientWebSocket ws) { var buffer = new byte[1024]; <span style='color: blue; font-weight: bold'>var result = await ws.ReceiveAsync(buffer, CancellationToken.None);</span> return Encoding.UTF8.GetString(buffer, 0, result.Count); } } </pre> <br /> 단지 비동기 구문만 살짝 더 곁들여져서 복잡한 듯하지만, 기존의 TCP 소켓과 사용법이 거의 유사해서 딱히 더 설명할 것이 없을 정도군요. ^^;<br /> <br /> 암튼, 그냥 어렵지 않으니 언제든 쉽게 적용할 수 있다는 정도였다는 것만 알고 넘어가도 되겠습니다.<br /> <br /> (<a target='tab' href='https://www.sysnet.pe.kr/bbs/DownloadAttachment.aspx?fid=2128&boardid=331301885'>첨부 파일은 이 글의 예제 코드를 포함</a>합니다.)<br /> <br /> <hr style='width: 50%' /><br /> <br /> 참고로, WebSocket을 아예 TCP Socket 레벨에서 다루고 싶다면 아래의 글이 도움이 될 것입니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > Writing a WebSocket server in C# ; <a target='tab' href='https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_server'>https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_server</a> C# WebSocket 서버 구현 ; <a target='tab' href='https://hgarchive.tistory.com/4'>https://hgarchive.tistory.com/4</a> Golang으로 직접 WebSocket 통신 구현해보기 ; <a target='tab' href='https://docs.google.com/document/d/e/2PACX-1vRrf1SD1k4FyXv1G-DPlDbX9F3KsNMnKogF4SrUNqkA9X5P8F-w2yTGzgDunctdpfHIfmoQZaFZ3jm4/pub'>https://docs.google.com/document/d/e/2PACX-1vRrf1SD1k4FyXv1G-DPlDbX9F3KsNMnKogF4SrUNqkA9X5P8F-w2yTGzgDunctdpfHIfmoQZaFZ3jm4/pub</a> </pre> <br /> 거의 <a target='tab' href='https://datatracker.ietf.org/doc/html/rfc6455'>RFC 6455</a> 규약대로 구현을 하고 있기 때문에 Web Socket에 대한 이해를 높일 수 있을 것입니다. 엄밀히 말해서, 단순한 TCP 통신의 한 사례일 뿐, 어쩌면 JavaScript가 이런 정도로까지 대중화하지 않았다면 나오지 않았을 기술입니다.<br /> <br /> <hr style='width: 50%' /><br /> <br /> 만약 이런 오류가 발생한다면?<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > 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. </pre> <br /> <a target='tab' href='https://mytears.tistory.com/81'>SSL 통신으로 열어</a>놓지 않은 WebSocket에 wss 프로토콜로 접근했기 때문입니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > System.Net.WebSockets.ClientWebSocket ws = new System.Net.WebSockets.ClientWebSocket(); await ws.ConnectAsync(new Uri("<span style='color: blue; font-weight: bold'>wss</span>://localhost:18000/"), CancellationToken.None); </pre> <br /> HTTP와 HTTPS의 관계처럼, WS와 WSS는 Secure Socket 통신의 여부를 결정합니다.<br /> <br /> <hr style='width: 50%' /><br /> <br /> 이런 오류가 발생한다면?<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > 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 </pre> <br /> 접속하려는 WebSocket 주소가 올바른지 확인해 볼 필요가 있습니다. 즉, HTTP 웹 서비스가 반응하는 경우 저런 오류가 발생하게 됩니다.<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
5852
(왼쪽의 숫자를 입력해야 합니다.)