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)
13345정성태5/9/20235035.NET Framework: 2117. C# - (OpenAI 기반의) Microsoft Semantic Kernel을 이용한 자연어 처리 [1]파일 다운로드1
13344정성태5/9/20236306.NET Framework: 2116. C# - OpenAI API 사용 - 지원 모델 목록 [1]파일 다운로드1
13343정성태5/9/20234198디버깅 기술: 192. Windbg - Hyper-V VM으로 이더넷 원격 디버깅 연결하는 방법
13342정성태5/8/20234120.NET Framework: 2115. System.Text.Json의 역직렬화 시 필드/속성 주의
13341정성태5/8/20233904닷넷: 2114. C# 12 - 모든 형식의 별칭(Using aliases for any type)
13340정성태5/8/20233919오류 유형: 857. Microsoft.Data.SqlClient.SqlException - 0x80131904
13339정성태5/6/20234612닷넷: 2113. C# 12 - 기본 생성자(Primary Constructors)
13338정성태5/6/20234098닷넷: 2112. C# 12 - 기본 람다 매개 변수파일 다운로드1
13337정성태5/5/20234618Linux: 59. dockerfile - docker exec로 container에 접속 시 자동으로 실행되는 코드 적용
13336정성태5/4/20234375.NET Framework: 2111. C# - 바이너리 출력 디렉터리와 연관된 csproj 설정
13335정성태4/30/20234503.NET Framework: 2110. C# - FFmpeg.AutoGen 라이브러리를 이용한 기본 프로젝트 구성 - Windows Forms파일 다운로드1
13334정성태4/29/20234151Windows: 250. Win32 C/C++ - Modal 메시지 루프 내에서 SetWindowsHookEx를 이용한 Thread 메시지 처리 방법
13333정성태4/28/20233625Windows: 249. Win32 C/C++ - 대화창 템플릿을 런타임에 코딩해서 사용파일 다운로드1
13332정성태4/27/20233719Windows: 248. Win32 C/C++ - 대화창을 위한 메시지 루프 사용자 정의파일 다운로드1
13331정성태4/27/20233742오류 유형: 856. dockerfile - 구 버전의 .NET Core 이미지 사용 시 apt update 오류
13330정성태4/26/20233409Windows: 247. Win32 C/C++ - CS_GLOBALCLASS 설명
13329정성태4/24/20233622Windows: 246. Win32 C/C++ - 직접 띄운 대화창 템플릿을 위한 Modal 메시지 루프 생성파일 다운로드1
13328정성태4/19/20233255VS.NET IDE: 184. Visual Studio - Fine Code Coverage에서 동작하지 않는 Fake/Shim 테스트
13327정성태4/19/20233677VS.NET IDE: 183. C# - .NET Core/5+ 환경에서 Fakes를 이용한 단위 테스트 방법
13326정성태4/18/20235046.NET Framework: 2109. C# - 닷넷 응용 프로그램에서 SQLite 사용 (System.Data.SQLite) [1]파일 다운로드1
13325정성태4/18/20234392스크립트: 48. 파이썬 - PostgreSQL의 with 문을 사용한 경우 연결 개체 누수
13324정성태4/17/20234234.NET Framework: 2108. C# - Octave의 "save -binary ..."로 생성한 바이너리 파일 분석파일 다운로드1
13323정성태4/16/20234133개발 환경 구성: 677. Octave에서 Excel read/write를 위한 io 패키지 설치
13322정성태4/15/20234898VS.NET IDE: 182. Visual Studio - 32비트로만 빌드된 ActiveX와 작업해야 한다면?
13321정성태4/14/20233734개발 환경 구성: 676. WSL/Linux Octave - Python 스크립트 연동
13320정성태4/13/20233739개발 환경 구성: 675. Windows Octave 8.1.0 - Python 스크립트 연동
1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...