내용 보기
작성자
관리자 (IP : 172.17.0.1)
날짜
2020-07-10 04:47
제목
[C#] 소켓 연결 시간 제한
|
소켓 연결 시간 제한
public bool TryConnect(string targetAddress, int connectTimeout)
{
Ping ping = new Ping();
try
{
PingReply reply = ping.Send(targetAddress, connectTimeout);
return (reply.Status == IPStatus.Success);
}
catch (Exception)
{
}
return false;
}
How to shorten socket.connect() timeout ?? ; http://forums.asp.net/p/1138952/1826854.aspx
public static Socket ConnectToserver(IPEndPoint endPoint, int port, int timeoutMs)
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
// do not block - do not want to be forced to wait on (too- long) timeout
socket.Blocking = false;
// initiate connection - will cause exception because we're not blocking
socket.Connect(endPoint);
return socket;
}
catch (SocketException socketException)
{
// check if this exception is for the expected 'Would Block' error
if (socketException.ErrorCode != 10035)
{
socket.Close();
// the error is not 'Would Block', so propogate the exception
throw;
}
// if we get here, the error is 'Would Block' so just continue execution }
// wait until connected or we timeout
int timeoutMicroseconds = timeoutMs * 1000;
if (socket.Poll(timeoutMicroseconds, SelectMode.SelectWrite) == false)
{
// timed out
socket.Close();
throw new Exception("The host failed to connect");
}
// *** AT THIS POINT socket.Connected SHOULD EQUAL TRUE BUT IS FALSE! ARGH!
// set socket back to blocking
socket.Blocking = true;
return socket;
}
}
|
출처1
출처2