Skip to content

Instantly share code, notes, and snippets.

@lisysolution
Last active April 19, 2016 14:51
Show Gist options
  • Save lisysolution/cc2b87f5ef256ba1e5ffb81bb903b63a to your computer and use it in GitHub Desktop.
Save lisysolution/cc2b87f5ef256ba1e5ffb81bb903b63a to your computer and use it in GitHub Desktop.
C# 비동기 소켓 연결 대기하는 방법 - 1개의 연결만 사용 하도록
while (true)
{
Socket _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IAsyncResult result = _socket.BeginConnect(host, port, (ar) =>
{
}, null);
// 연결이 될때 까지 timeout 시간 동안 대기 한다.
result.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(timeout), false);
try
{
/*
비동기 소켓 연결에서는 BeginConnect 와 EndConnect 를 항상 한쌍으로 호출해 준다.
한쌍으로 호출해 주지 않으면 연결 실패로 인하 재접속으로 인하여 불필요한 Connection 이 발생하게 된다.
*/
_socket.EndConnect(result);
break;
}
catch { }
continue;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment