성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] Java - How to use the Foreign Funct...
[정성태] 제가 큰 실수를 했군요. ^^; 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'>Socket.Receive 메서드의 SocketFlags.Peek 동작을 이용해 소켓 연결 유무를 확인?</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#: How to determine if a TCPClient has been disconnected ; <a target='tab' href='https://social.msdn.microsoft.com/Forums/en-US/c857cad5-2eb6-4b6c-b0b5-7f4ce320c5cd/c-how-to-determine-if-a-tcpclient-has-been-disconnected?forum=netfxnetcom'>https://social.msdn.microsoft.com/Forums/en-US/c857cad5-2eb6-4b6c-b0b5-7f4ce320c5cd/c-how-to-determine-if-a-tcpclient-has-been-disconnected?forum=netfxnetcom</a> </pre> <br /> 위의 글에 보면, TcpClient 객체의 소켓 연결이 끊겼는지에 대한 판단으로 다음과 같은 답변이 6개의 추천을 받고 있는데요. <br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > // <a target='tab' href='https://stackoverflow.com/questions/101708/tcpclient-connected-returns-true-yet-client-is-not-connected-what-can-i-use-ins'>https://stackoverflow.com/questions/101708/tcpclient-connected-returns-true-yet-client-is-not-connected-what-can-i-use-ins</a> // Detect if client disconnected if( tcp.Client.<span style='color: blue; font-weight: bold'>Poll( 0, SelectMode.SelectRead )</span> ) { byte[] buff = new byte[1]; if( <span style='color: blue; font-weight: bold'>tcp.Client.Receive( buff, SocketFlags.Peek )</span> == 0 ) { // Client disconnected bClosed = true; } } </pre> <br /> Win32 API 개발자라면 Message Loop의 <a target='tab' href='https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getmessage'>GetMessage</a>/<a target='tab' href='https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-peekmessagea'>PeekMessage</a> Win32 API를 연상하면서 "Peek" 인자를 주면 소켓의 수신 버퍼에 데이터가 있는지만 확인하고 바로 반환하는 거라고 오해할 수 있는데요. SocketFlags.Peek 인자를 주었어도 Receive 메서드는 blocking 함수라는 것을 잊으면 안됩니다.<br /> <br /> 이로 인해, 만약에 여러분들의 UI 스레드와 같은 식의 주요 작업자 스레드에서 소켓이 연결되었는지 확인하기 위해 저런 식으로 Receive 메서드를 호출했다가는 자칫 무한 대기(hang)로 빠질 수 있습니다.<br /> <br /> <hr style='width: 50%' /><br /> <br /> 일단, 주의사항은 그렇긴 하지만 위에서 소개한 코드가 그런대로 잘 동작하긴 합니다. 한번 동작을 분석해 볼까요? ^^<br /> <br /> <a target='tab' href='https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.socket.poll'>Poll 메서드</a>에 SelectMode.SelectRead 옵션을 주는 경우, 다음과 같이 3가지 상황에서 true를 반환하게 됩니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > 1) true if Listen has been called and a connection is pending; 2) true if data is available for reading; 3) true if the connection has been closed, reset, or terminated; otherwise, returns false. </pre> <br /> 일단, 클라이언트 측 소켓이라고 한정하면 1번은 해당 사항이 없습니다. 따라서 "데이터 수신이 되었거나, 연결이 끊어졌으면 true를 반환한다"라고 범위를 좁힐 수 있습니다.<br /> <br /> 이에 따라 서버가 Close를 호출하면, 클라이언트 측에서는 Poll 메서드가 true를 반환하게 됩니다. 그리고 Receive(..., Peek)는 0을 반환하게 되고 의도했던 것처럼 연결이 끊겼음을 알아낼 수 있습니다. 하지만, 헛점도 있습니다. 예를 들어, 서버가 다음과 같이 Send를 한 다음 바로 연결을 종료하고,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > while (true) { TcpClient clientSocket = serverSock.AcceptTcpClient(); Console.WriteLine("accepted"); byte[] buf = new byte[4]; <span style='color: blue; font-weight: bold'>clientSocket.Client.Send(buf); clientSocket.Close();</span> Thread.Sleep(Timeout.Infinite); continue; } </pre> <br /> 이 상태에서 클라이언트가 Receive 없이 IsConnected를 호출하게 되면 연결은 계속 맺어져 있다고 나옵니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > private static void ClientFunc(object obj) { TcpClient clientSocket = new TcpClient(); string[] args = Environment.GetCommandLineArgs(); string serverAddress = "localhost"; clientSocket.Connect(serverAddress, 5000); if (serverAddress == "localhost") { Thread.Sleep(1000); } bool loop = true; <span style='color: blue; font-weight: bold'> while (loop) { loop = IsConnected(clientSocket); // True 반환 Console.WriteLine(loop); Thread.Sleep(1000); }</span> clientSocket.Close(); } </pre> <br /> 이때 netstate를 실행해 소켓의 상태를 보면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > c:>netstat -ano |findstr "5000" TCP 0.0.0.0:5000 0.0.0.0:0 LISTENING 10380 TCP 127.0.0.1:5000 127.0.0.1:57373 <span style='color: blue; font-weight: bold'>FIN_WAIT_2</span> 10380 TCP 127.0.0.1:57373 127.0.0.1:5000 <span style='color: blue; font-weight: bold'>CLOSE_WAIT</span> 10380 </pre> <br /> 서버 소켓은 close를 호출했기 때문에 FIN_WAIT_2 상태로 빠졌고, 클라이언트는 CLOSE_WAIT으로 진입했습니다. (참조: <a target='tab' href='http://www.sysnet.pe.kr/2/0/1334'>"코드로 재현하는 소켓 상태(FIN_WAIT1, FIN_WAIT2, TIME_WAIT, CLOSE_WAIT, LAST_WAIT)"</a>)<br /> <br /> 이 외에, 다중 스레드에서 IsConnected 메서드를 호출하는 경우 무한 대기에 빠질 수 있는 조건이 있습니다. 예를 들어, 서버가 Send만 하고 Close를 호출하지 않은 상황에서 클라이언트 측 소켓이 Poll(..., SelectRead)를 호출하면 true를 반환하게 됩니다. 따라서 if 문 내부로 진입하게 되는데, 이때 스레드 스위칭이 발생해서 다른 스레드에서 동일한 소켓 자원으로 Receive를 호출하여 수신 버퍼의 데이터를 모두 읽어간다면 어떻게 될까요? 당연히! 다시 Poll 메서드를 호출한 스레드가 스케쥴링되는 경우 Receive(..., Peek)라고 호출하면 무한 대기(hang)에 빠지게 됩니다. 물론, 이런 오류는 쉽게 재현되지 않기 때문에 다중 스레드에서 소켓을 사용하는 경우 IsConnected(...)처럼 사용했다가는 머리를 쥐어뜯는 상황으로 이어질 수 있습니다.<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;' > using System; using System.Net; using System.Net.Sockets; using System.Threading; class Program { static void Main(string[] args) { Thread serverThread = new Thread(serverFunc); serverThread.IsBackground = true; serverThread.Start(); Console.ReadLine(); } private static void serverFunc(object obj) { TcpListener serverSock = new TcpListener(IPAddress.Any, 5000); serverSock.Start(5); { Thread clientThread = new Thread(ClientFunc); clientThread.IsBackground = true; clientThread.Start(); } while (true) { TcpClient clientSocket = serverSock.AcceptTcpClient(); Console.WriteLine("accepted"); byte[] buf = new byte[4]; clientSocket.Client.Send(buf); Thread.Sleep(Timeout.Infinite); continue; } } private static void ClientFunc(object obj) { TcpClient clientSocket = new TcpClient(); string[] args = Environment.GetCommandLineArgs(); string serverAddress = "localhost"; clientSocket.Connect(serverAddress, 5000); if (serverAddress == "localhost") { Thread.Sleep(1000); } bool loop = true; EventWaitHandle ewh = new EventWaitHandle(false, EventResetMode.ManualReset); while (loop) { ThreadPool.QueueUserWorkItem( (arg) => { Thread.Sleep(1000); byte[] buf = new byte[1024]; int readLen = <span style='color: blue; font-weight: bold'>clientSocket.Client.Receive(buf);</span> Console.WriteLine("Client.Receive: " + readLen); <span style='color: blue; font-weight: bold'>((EventWaitHandle)(arg)).Set();</span> } , ewh); loop = IsConnected(ewh, clientSocket); Console.WriteLine(loop); Thread.Sleep(1000); } clientSocket.Close(); } public static bool IsConnected(EventWaitHandle ewh, TcpClient clientSocket) { try { if (clientSocket.Client.Poll(0, SelectMode.SelectRead)) { <span style='color: blue; font-weight: bold'>ewh.WaitOne();</span> byte[] buff = new byte[1]; if (clientSocket.Client.Receive(buff, SocketFlags.Peek) == 0) // 무한 대기(hang) 현상 발생 { return false; } } } catch { } return true; } } </pre> <br /> 위의 코드를 실행하면 Poll 메서드는 수신 버퍼에 데이터가 있으므로 true를 반환해서 if 문 내로 진입했다가 WaitOne으로 시뮬레이션한 스레드 스위칭이 발생한 후 다른 스레드에서 Receive를 하는 바람에 이후 Receive(..., Peek)에서 무한 대기 현상이 발생하는 것을 확인할 수 있습니다.<br /> <br /> <hr style='width: 50%' /><br /> <br /> 아쉬운 대로, 일단 무한 대기 현상만 수정해 보겠습니다. 이를 위해서는 Receive를 호출해서는 안되고 실제로 '수신 버퍼'에 데이터가 있는지에 대한 체크만 해주는 함수를 호출해야 합니다. 이를 위해 IOControl 메서드를 쓸 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > public static bool IsConnected(EventWaitHandle ewh, TcpClient clientSocket) { try { if (clientSocket.Client.Poll(0, SelectMode.SelectRead)) { ewh.WaitOne(); byte[] buff = new byte[1]; <span style='color: blue; font-weight: bold'> // DataToRead == 0x4004667f (0n1074030207) byte[] dataToRead = new byte[4]; clientSocket.Client.IOControl(IOControlCode.DataToRead, null, dataToRead); if (BitConverter.ToInt32(dataToRead, 0) == 0) { return false; }</span> //if (clientSocket.Client.Receive(buff, SocketFlags.Peek) == 0) //{ // return false; //} } } catch { } return true; } </pre> <br /> 또는, 해당 IOControl 호출과 동일한 역할을 수행하는 <a target='tab' href='https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.socket.available'>Socket.Available</a> 속성을 조사하면 됩니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > public static bool IsConnected(EventWaitHandle ewh, TcpClient clientSocket) { try { if (clientSocket.Client.Poll(0, SelectMode.SelectRead)) { ewh.WaitOne(); byte[] buff = new byte[1]; <span style='color: blue; font-weight: bold'>return clientSocket.Client.Available != 0;</span> } } catch { } return true; } </pre> <br /> 비록 이것으로 무한 대기(hang) 현상을 막을 수는 있지만, 아쉽게도 저 상황에서는 연결이 끊겼다는 잘못된 판단을 내리게 됩니다. 결국, 이런 방식으로는 소켓 연결이 끊겼는지에 대한 올바른 함수를 만들 수는 없습니다.<br /> <br /> (<a target='tab' href='http://www.sysnet.pe.kr/bbs/DownloadAttachment.aspx?fid=905&boardid=331301885'>첨부한 파일은 이 글의 예제 코드를 포함</a>합니다.)<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
1705
(왼쪽의 숫자를 입력해야 합니다.)