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)
13254정성태2/10/20234387Windows: 223. (WMI 쿼리를 위한) PowerShell 문자열 escape 처리
13253정성태2/9/20235162Windows: 222. C# - 다른 윈도우 프로그램이 실행되었음을 인식하는 방법파일 다운로드1
13252정성태2/9/20233998오류 유형: 844. ssh로 명령어 수행 시 멈춤 현상
13251정성태2/8/20234442스크립트: 44. 파이썬의 3가지 스레드 ID
13250정성태2/8/20236258오류 유형: 843. System.InvalidOperationException - Unable to configure HTTPS endpoint
13249정성태2/7/20235090오류 유형: 842. 리눅스 - You must wait longer to change your password
13248정성태2/7/20234160오류 유형: 841. 리눅스 - [사용자 계정] is not in the sudoers file. This incident will be reported.
13247정성태2/7/20235062VS.NET IDE: 180. Visual Studio - 닷넷 소스 코드 디버깅 중 "Decompile source code"가 동작하는 않는 문제
13246정성태2/6/20234183개발 환경 구성: 664. Hyper-V에 설치한 리눅스 VM의 VHD 크기 늘리는 방법 - 두 번째 이야기
13245정성태2/6/20234755.NET Framework: 2093. C# - PEM 파일을 이용한 RSA 개인키/공개키 설정 방법파일 다운로드1
13244정성태2/5/20234103VS.NET IDE: 179. Visual Studio - External Tools에 Shell 내장 명령어 등록
13243정성태2/5/20234961디버깅 기술: 190. windbg - Win32 API 호출 시점에 BP 거는 방법 [1]
13242정성태2/4/20234411디버깅 기술: 189. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.UnauthorizedAccessException
13241정성태2/3/20233913디버깅 기술: 188. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.IO.FileNotFoundException
13240정성태2/1/20234068디버깅 기술: 187. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.Web.HttpException
13239정성태2/1/20233728디버깅 기술: 186. C# - CacheDependency의 숨겨진 예외 - System.Web.HttpException
13238정성태1/31/20235811.NET Framework: 2092. IIS 웹 사이트를 TLS 1.2 또는 TLS 1.3 프로토콜로만 운영하는 방법
13237정성태1/30/20235468.NET Framework: 2091. C# - 웹 사이트가 어떤 버전의 TLS/SSL을 지원하는지 확인하는 방법
13236정성태1/29/20235076개발 환경 구성: 663. openssl을 이용해 인트라넷 IIS 사이트의 SSL 인증서 생성
13235정성태1/29/20234636개발 환경 구성: 662. openssl - 윈도우 환경의 명령행에서 SAN 적용하는 방법
13234정성태1/28/20235721개발 환경 구성: 661. dnSpy를 이용해 소스 코드가 없는 .NET 어셈블리의 코드를 변경하는 방법 [1]
13233정성태1/28/20237041오류 유형: 840. C# - WebClient로 https 호출 시 "The request was aborted: Could not create SSL/TLS secure channel" 예외 발생
13232정성태1/27/20234804스크립트: 43. uwsgi의 --processes와 --threads 옵션
13231정성태1/27/20233728오류 유형: 839. python - TypeError: '...' object is not callable
13230정성태1/26/20234100개발 환경 구성: 660. WSL 2 내부로부터 호스트 측의 네트워크로 UDP 데이터가 1개의 패킷으로만 제한되는 문제
13229정성태1/25/20235094.NET Framework: 2090. C# - UDP Datagram의 최대 크기
1  2  3  4  5  6  7  8  9  10  11  12  13  14  [15]  ...