Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

C# - Socket.Close 시 Socket.Receive 메서드에서 예외가 발생하는 문제

아래와 같은 질문이 있는데요,

socket 종료 시 reveive수신부에서 에러 나는거 처리 문의
; https://www.sysnet.pe.kr/3/0/5693

정리해 보면 다음의 코드로 재현할 수 있습니다.

using System.Net.Sockets;

Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

socket.Connect("127.0.0.1", 80);

ThreadPool.QueueUserWorkItem(socketClose, socket);

byte[] buffer = new byte[4096];
socket.Receive(buffer); // 소켓 Receive로 스레드 대기
socket.Close();

void socketClose(object? state)
{
    // 1초 후 Socket.Close 호출
    Thread.Sleep(1000);
    (state as Socket)?.Close();
}

위의 코드를 실행하면 Receive 호출에서 System.Net.Sockets.SocketException 예외가 발생합니다.

Unhandled exception. System.Net.Sockets.SocketException (10053): An established connection was aborted by the software in your host machine.
   at System.Net.Sockets.Socket.Receive(Byte[] buffer)
   at Program.<Main>$(String[] args) in C:\...\ConsoleApp1\ConsoleApp1\Program.cs:line 11

C/C++로 소켓을 다뤄보신 분들은 아시겠지만, 사실 socket API 자체에서는 예외라는 것이 없습니다. 즉, .NET의 Socket은 socket API의 recv 함수 호출 결과에 대해 일부러 예외를 발생시키는 것입니다.

실제로 소스 코드를 보면,

referencesource/System/net/System/Net/Sockets/Socket.cs
; https://github.com/microsoft/referencesource/blob/master/System/net/System/Net/Sockets/Socket.cs

public int Receive(byte[] buffer)
{
    return Receive(buffer, 0, buffer != null ? buffer.Length : 0, SocketFlags.None);
}

// Receives data from a connected socket into a specific location of the receive buffer.
public int Receive(byte[] buffer, int offset, int size, SocketFlags socketFlags)
{
    SocketError errorCode;
    int bytesTransferred = Receive(buffer, offset, size, socketFlags, out errorCode);
    if (errorCode != SocketError.Success)
    {
        throw new SocketException((int)errorCode);
    }
    return bytesTransferred;
}

overload된 Receive 메서드들 중에 예외를 발생시키는 경우가 있는 것에 불과합니다. 따라서, 예외를 발생시키지 않는 버전의 Receive 메서드를 사용하면,

byte[] buffer = new byte[4096];

socket.Receive(buffer, 0, buffer.Length, SocketFlags.None, out SocketError errorCode);
if (errorCode != SocketError.Success)
{
    Console.WriteLine("Receive error");
}

이제는 Socket.Close가 발생해도 예외 없이 "out SocketError errorCode"의 인자로 결과를 알 수 있습니다.




그리고 해당 질문의 덧글을 보면 UDP 소켓에 대한 ReceiveFrom 메서드의 오류 질문이 나오는데요,

using System.Net;
using System.Net.Sockets;

Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Connect(IPAddress.Loopback, 15000); // TCP와는 달리 연결하지는 않고, Bind 역할만 담당

ThreadPool.QueueUserWorkItem(socketClose, socket);

byte[] buffer = new byte[4096];
EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);
socket.ReceiveFrom(buffer, ref remoteEP); // 소켓 ReceiveFrom으로 스레드 대기

void socketClose(object? state)
{
    Thread.Sleep(1000);
    (state as Socket)?.Close();
}

/* 예외 발생
Unhandled exception. System.Net.Sockets.SocketException (10004): A blocking operation was interrupted by a call to WSACancelBlockingCall.
   at System.Net.Sockets.Socket.ReceiveFrom(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags, EndPoint& remoteEP)
   at System.Net.Sockets.Socket.ReceiveFrom(Byte[] buffer, EndPoint& remoteEP)
   at Program.
$(String[] args) in C:\...\ConsoleApp1\ConsoleApp2\Program.cs:line 12 */

아쉽게도 ReceiveFrom의 경우에는 예외를 발생시키지 않는 버전의 메서드가 없습니다. 따라서, 만약 이런 경우에도 예외를 원하지 않는다면 Receive 호출로 대체해야 합니다.

Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Connect(IPAddress.Loopback, 15000); // 바인딩 역할

ThreadPool.QueueUserWorkItem(socketClose, socket);

byte[] buffer = new byte[4096];
socket.Receive(buffer, 0, buffer.Length, SocketFlags.None, out SocketError errorCode);
if (errorCode != SocketError.Success)
{
    Console.WriteLine("Receive error");
}

void socketClose(object? state)
{
    Thread.Sleep(1000);
    (state as Socket)?.Close();
}

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




그나저나, Close 시 Receive에서 발생하는 (어차피 try/catch로 처리할) 예외가 얼마나 성능에 영향을 미칠 수 있을까요? 물론, 예외가 발생하면 일반적인 코드보다 성능이 느려지는 것은 맞습니다. 그렇기 때문에 Int.Parse와 같은 메서드도 예외가 발생하지 않는 버전의 Int.TryParse를 제공하게 된 것입니다.

하지만, Receive는 어떨까요? 대부분의 경우 우리는 네트워크 코드를 프로토콜을 결정해 Send/Receive를 하게 됩니다. 즉, 일반적인 통신에서는 Receive에서 예외가 발생할 수 있는 여지가 거의 없습니다. 가령, 네트워크가 강제로 끊겼거나 하는 등의 상황이거나... 아니면 잘못 만든 코드로 인해 Socket.Close가 발생하는 경우일 것입니다.

그런 상황에서 발생할 예외의 횟수라면 엄밀히 말해서 성능에 거의 영향이 없습니다. 아마도 특정 시간 내에서 유의미한 성능 저하를 보려면 상호 간의 네트워크 통신을 엄청난 고속으로 실행하면서도, 그 통신에 자주 Close 상황이 있어야 한다는 것인데... 현실적으로 그런 상황은 모든 통신 프로토콜에 버그가 있다고 봐야 합니다.

그러니, 너무 예외 발생에 신경을 쓰기보다는 좀 더 성능에 유의미하게 영향을 미치는 코드를 위주로 우선순위를 두고 접근하는 것을 권장합니다.

(심지어 질문하신 분은, Receive의 out 인자에 대해 초기화하는 것까지도 속도 저하를 걱정하는데... 그 코드로 인한 속도 저하를 걱정해야 한다면 애당초 C#으로 해당 프로그램을 개발하는 것이 더 문제입니다. 그런 상황이라면 C/C++로 제작하는 것이 맞습니다.)




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 11/1/2022]

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)
13378정성태6/22/20233174오류 유형: 868. docker - build 시 "CANCELED ..." 뜨는 문제
13377정성태6/22/20237004오류 유형: 867. 파이썬 mysqlclient 2.2.x 설치 시 "Specify MYSQLCLIENT_CFLAGS and MYSQLCLIENT_LDFLAGS env vars manually" 오류
13376정성태6/21/20233374.NET Framework: 2129. C# - Polly를 이용한 클라이언트 측의 요청 재시도파일 다운로드1
13375정성태6/20/20233057스크립트: 50. Transformers (신경망 언어모델 라이브러리) 강좌 - 2장 코드 실행 결과
13374정성태6/20/20233170오류 유형: 866. 파이썬 - <class 'AttributeError'> module 'flask.json' has no attribute 'JSONEncoder'
13373정성태6/19/20234463오류 유형: 865. 파이썬 - pymssql 설치 관련 오류 정리
13372정성태6/15/20233176개발 환경 구성: 682. SQL Server TLS 통신을 위해 사용되는 키 길이 확인 방법
13371정성태6/15/20233206개발 환경 구성: 681. openssl - 인증서 버전(V1 / V3)
13370정성태6/14/20233354개발 환경 구성: 680. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 - TLS 1.2 지원
13369정성태6/13/20233175개발 환경 구성: 679. PyCharm(을 비롯해 JetBrains에 속한 여타) IDE에서 내부 Window들의 탭이 없어진 경우
13368정성태6/13/20233321개발 환경 구성: 678. openssl로 생성한 인증서를 SQL Server의 암호화 인증서로 설정하는 방법
13367정성태6/10/20233428오류 유형: 864. openssl로 만든 pfx 인증서를 Windows Server 2016 이하에서 등록 시 "The password you entered is incorrect" 오류 발생
13366정성태6/10/20233197.NET Framework: 2128. C# - 윈도우 시스템에서 지원하는 암호화 목록(Cipher Suites) 나열파일 다운로드1
13365정성태6/8/20232941오류 유형: 863. MODIFY FILE encountered operating system error 112(failed to retrieve text for this error. Reason: 15105)
13364정성태6/8/20233749.NET Framework: 2127. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 [1]
13363정성태6/7/20233321스크립트: 49. 파이썬 - "Transformers (신경망 언어모델 라이브러리) 강좌" - 1장 2절 코드 실행 결과
13362정성태6/1/20233241.NET Framework: 2126. C# - 서버 측의 요청 제어 (Microsoft.AspNetCore.RateLimiting)파일 다운로드1
13361정성태5/31/20233697오류 유형: 862. Facebook - ASP.NET/WebClient 사용 시 graph.facebook.com/me 호출에 대해 403 Forbidden 오류
13360정성태5/31/20233065오류 유형: 861. WSL/docker - failed to start shim: start failed: io.containerd.runc.v2: create new shim socket
13359정성태5/19/20233398오류 유형: 860. Docker Desktop - k8s 초기화 무한 반복한다면?
13358정성태5/17/20233708.NET Framework: 2125. C# - Semantic Kernel의 Semantic Memory 사용 예제 [1]파일 다운로드1
13357정성태5/16/20233516.NET Framework: 2124. C# - Semantic Kernel의 Planner 사용 예제파일 다운로드1
13356정성태5/15/20233830DDK: 10. Device Driver 테스트 설치 관련 오류 (Code 37, Code 31) 및 인증서 관련 정리
13355정성태5/12/20233758.NET Framework: 2123. C# - Semantic Kernel의 ChatGPT 대화 구현 [1]파일 다운로드1
13354정성태5/12/20234013.NET Framework: 2122. C# - "Use Unicode UTF-8 for worldwide language support" 설정을 한 경우, 한글 입력이 '\0' 문자로 처리
13352정성태5/12/20233651.NET Framework: 2121. C# - Semantic Kernel의 대화 문맥 유지파일 다운로드1
1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...