C#的tcpClient的Connect连接超时问题。
用tcpclient的Connect连接服务器时如何设置连接超时的时间?在若干时间后抛出异常?...
用tcpclient的Connect连接服务器时如何设置连接超时的时间?在若干时间后抛出异常?
展开
2个回答
展开全部
class TimeOutSocket
{
privatestaticbool IsConnectionSuccessful = false;
privatestatic Exception socketexception;
privatestatic ManualResetEvent TimeoutObject = new ManualResetEvent(false);
publicstatic TcpClient TryConnect(IPEndPoint remoteEndPoint, int timeoutMiliSecond)
{
TimeoutObject.Reset();
socketexception = null;
string serverip = Convert.ToString(remoteEndPoint.Address);
int serverport = remoteEndPoint.Port;
TcpClient tcpclient = new TcpClient();
tcpclient.BeginConnect(serverip, serverport,
new AsyncCallback(CallBackMethod), tcpclient);
if (TimeoutObject.WaitOne(timeoutMiliSecond, false))
{
if (IsConnectionSuccessful)
{
return tcpclient;
}
else
{
throw socketexception;
}
}
else
{
tcpclient.Close();
thrownew TimeoutException("TimeOut Exception");
}
}
privatestaticvoid CallBackMethod(IAsyncResult asyncresult)
{
try
{
IsConnectionSuccessful = false;
TcpClient tcpclient = asyncresult.AsyncState as TcpClient;
if (tcpclient.Client != null)
{
tcpclient.EndConnect(asyncresult);
IsConnectionSuccessful = true;
}
}
catch (Exception ex)
{
IsConnectionSuccessful = false;
socketexception = ex;
}
finally
{
TimeoutObject.Set();
}
}
}
{
privatestaticbool IsConnectionSuccessful = false;
privatestatic Exception socketexception;
privatestatic ManualResetEvent TimeoutObject = new ManualResetEvent(false);
publicstatic TcpClient TryConnect(IPEndPoint remoteEndPoint, int timeoutMiliSecond)
{
TimeoutObject.Reset();
socketexception = null;
string serverip = Convert.ToString(remoteEndPoint.Address);
int serverport = remoteEndPoint.Port;
TcpClient tcpclient = new TcpClient();
tcpclient.BeginConnect(serverip, serverport,
new AsyncCallback(CallBackMethod), tcpclient);
if (TimeoutObject.WaitOne(timeoutMiliSecond, false))
{
if (IsConnectionSuccessful)
{
return tcpclient;
}
else
{
throw socketexception;
}
}
else
{
tcpclient.Close();
thrownew TimeoutException("TimeOut Exception");
}
}
privatestaticvoid CallBackMethod(IAsyncResult asyncresult)
{
try
{
IsConnectionSuccessful = false;
TcpClient tcpclient = asyncresult.AsyncState as TcpClient;
if (tcpclient.Client != null)
{
tcpclient.EndConnect(asyncresult);
IsConnectionSuccessful = true;
}
}
catch (Exception ex)
{
IsConnectionSuccessful = false;
socketexception = ex;
}
finally
{
TimeoutObject.Set();
}
}
}
参考资料: http://blog.csdn.net/luols/article/details/5835081
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
Storm代理
2023-07-25 广告
2023-07-25 广告
StormProxies是一家国内优质海外HTTP代理商,拥有一个庞大的IP资源池,覆盖200多个地区,IP数量大且匿名度高。其优点还包括超高并发、稳定高效、技术服务等特点,同时提供HTTP、HTTPS以及SOCKS5协议支持。此外,Sto...
点击进入详情页
本回答由Storm代理提供
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询