Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)
(시리즈 글이 6개 있습니다.)
.NET Framework: 487. Socket.Receive 메서드의 SocketFlags.Peek 동작을 이용해 소켓 연결 유무를 확인?
; https://www.sysnet.pe.kr/2/0/1824

.NET Framework: 488. TCP 소켓 연결의 해제를 알 수 있는 방법
; https://www.sysnet.pe.kr/2/0/1825

닷넷: 2204. C# - TCP KeepAlive에 새로 추가된 Retry 옵션
; https://www.sysnet.pe.kr/2/0/13531

닷넷: 2206. C# - TCP KeepAlive의 서버 측 구현
; https://www.sysnet.pe.kr/2/0/13533

Windows: 255. (디버거의 영향 등으로) 대상 프로세스가 멈추면 Socket KeepAlive로 연결이 끊길까요?
; https://www.sysnet.pe.kr/2/0/13546

Windows: 256. C# - Server socket이 닫히면 Accept 시켰던 자식 소켓이 닫힐까요?
; https://www.sysnet.pe.kr/2/0/13550




C# - Server socket이 닫히면 Accept 시켰던 자식 소켓이 닫힐까요?

지인으로부터 제목과 같은 질문을 받았습니다. 저는 이론상 서버 소켓이 닫힌다고 해서 그것과 연결됐었던 자식 소켓들이 닫히지는 않을 거라고 했습니다.

그래도 이런 경우 ^^ 꼭 테스트를 해봐야 합니다.

예제는 대략 다음과 같이 만들어 두고,

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

namespace ConsoleApp2;

internal class Program
{
    static void Main(string[] args)
    {
        Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        IPEndPoint ep = new IPEndPoint(IPAddress.Any, 16000);
        Console.WriteLine(ep);

        socket.Bind(ep);
        socket.Listen(10);
        bool accepted = false;

        Thread t = new Thread(() =>
        {
            byte[] buffer = new byte[10];
            Socket client = socket.Accept();
            Console.WriteLine($"Client connected: {client.LocalEndPoint}:{client.RemoteEndPoint}");
            accepted = true;

            while (true)
            {
                int recvBytes = client.Receive(buffer);
                if (recvBytes <= 0)
                {
                    Console.WriteLine("Client disconnected.");
                    break;
                }

                Thread.Sleep(1000);
            }

            client.Close();
        });
        t.Start();

        while (true)
        {
            if (accepted == true)
            {
                Console.WriteLine("Server closed.");
                socket.Close();
                break;
            }
            else
            {
                Thread.Sleep(16);
                Console.Write(".");
            }
        }

        Console.WriteLine("Press any key to exit...");
        Console.ReadLine();
    }
}

클라이언트가 접속하게 만들면 서버 측 출력이 이런 식으로 나옵니다.

0.0.0.0:16000
...........[생략]....................
Client connected: 172.17.0.2:16000:172.17.0.1:52110
Server closed.
Press any key to exit...

화면에 "Client disconnected." 메시지가 없으니, 서버 소켓을 닫아도 클라이언트 소켓은 여전히 접속 중인 것입니다.




혹시나 옵션이 있을까 싶어 찾아봤는데요,

IOControlCode Enum
; https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.iocontrolcode

SOL_SOCKET Socket Options
; https://learn.microsoft.com/en-us/windows/win32/winsock/sol-socket-socket-options

IPPROTO_TCP socket options
; https://learn.microsoft.com/en-us/windows/win32/winsock/ipproto-tcp-socket-options

제가 찾는 한에서는 없었습니다. 검색으로도 딱히 안 되는 것을 보면, 이런 기능은 없는 듯합니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 2/11/2024]

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)
13711정성태8/13/20243122Linux: 77. C# / Linux - zombie process (defunct process)파일 다운로드1
13710정성태8/8/20243183닷넷: 2294. C# 13 - (6) iterator 또는 비동기 메서드에서 ref와 unsafe 사용을 부분적으로 허용파일 다운로드1
13709정성태8/7/20243051닷넷: 2293. C# - safe/unsafe 문맥에 대한 C# 13의 (하위 호환을 깨는) 변화파일 다운로드1
13708정성태8/7/20242698개발 환경 구성: 719. ffmpeg / YoutubeExplode - mp4 동영상 파일로부터 Audio 파일 추출
13707정성태8/6/20243118닷넷: 2292. C# - 자식 프로세스의 출력이 4,096보다 많은 경우 Process.WaitForExit 호출 시 hang 현상파일 다운로드1
13706정성태8/5/20243167개발 환경 구성: 718. Hyper-V - 리눅스 VM에 새로운 디스크 추가
13705정성태8/4/20243515닷넷: 2291. C# 13 - (5) params 인자 타입으로 컬렉션 허용파일 다운로드1
13704정성태8/2/20243294닷넷: 2290. C# - 간이 dotnet-dump 프로그램 만들기파일 다운로드1
13703정성태8/1/20243455닷넷: 2289. "dotnet-dump ps" 명령어가 닷넷 프로세스를 찾는 방법
13702정성태7/31/20243320닷넷: 2288. Collection 식을 지원하는 사용자 정의 타입을 CollectionBuilder 특성으로 성능 보완파일 다운로드1
13701정성태7/30/20243312닷넷: 2287. C# 13 - (4) Indexer를 이용한 개체 초기화 구문에서 System.Index 연산자 허용파일 다운로드1
13700정성태7/29/20243004디버깅 기술: 200. DLL Export/Import의 Hint 의미
13699정성태7/27/20243143닷넷: 2286. C# 13 - (3) Monitor를 대체할 Lock 타입파일 다운로드1
13698정성태7/27/20243064닷넷: 2285. C# - async 메서드에서의 System.Threading.Lock 잠금 처리파일 다운로드1
13697정성태7/26/20243238닷넷: 2284. C# - async 메서드에서의 lock/Monitor.Enter/Exit 잠금 처리파일 다운로드1
13696정성태7/26/20243132오류 유형: 920. dotnet publish - error NETSDK1047: Assets file '...\obj\project.assets.json' doesn't have a target for '...'
13695정성태7/25/20242814닷넷: 2283. C# - Lock / Wait 상태에서도 STA COM 메서드 호출 처리파일 다운로드1
13694정성태7/25/20243070닷넷: 2282. C# - ASP.NET Core Web App의 Request 용량 상한값 (Kestrel, IIS)
13693정성태7/24/20242956개발 환경 구성: 717. Visual Studio - C# 프로젝트에서 레지스트리에 등록하지 않은 COM 개체 참조 및 사용 방법파일 다운로드1
13692정성태7/24/20243522디버깅 기술: 199. Windbg - 리눅스에서 뜬 닷넷 응용 프로그램 덤프 파일에 포함된 DLL의 Export Directory 탐색
13691정성태7/23/20243022디버깅 기술: 198. Windbg - 스레드의 Win32 Message Queue 정보 조회
13690정성태7/23/20242760오류 유형: 919. Visual C++ 리눅스 프로젝트 - error : ‘u8’ was not declared in this scope
13689정성태7/22/20243228디버깅 기술: 197. Windbg - PE 포맷의 Export Directory 탐색
13688정성태7/21/20243065닷넷: 2281. C# - Lock / Wait 상태에서도 일부 Win32 메시지 처리파일 다운로드1
13687정성태7/19/20243303닷넷: 2280. C# - PostThreadMessage로 보낸 메시지를 Windows Forms에서 수신하는 방법파일 다운로드1
13686정성태7/19/20243360오류 유형: 918. Visual Studio - ATL Simple Object 추가 시 error C2065: 'IDR_...': undeclared identifier
1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...