C# Socket連接請求超時機制實現(xiàn)代碼分享
.Net的System.Net.Sockets.TcpClient和System.Net.Sockets.Socket都沒有直接為Connect/BeginConnect提供超時控制機制。因此,或者發(fā)生網絡故障時,客戶端連接請求會等待很長一段時間,直到拋出異常。默認的等待時間長達20~30s。.Net Socket庫的SocketOptionName.SendTimeout提供了控制發(fā)送數(shù)據(jù)的超時時間,但并非本文討論的連接請求的超時時間。
實現(xiàn)
下面是實現(xiàn)的關鍵代碼:
class TimeOutSocket
{
private static bool IsConnectionSuccessful = false;
private static Exception socketexception;
private static ManualResetEvent TimeoutObject = new ManualResetEvent(false);
public static 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();
throw new TimeoutException("TimeOut Exception");
}
}
private static void 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();
}
}
}
相關文章
C#中圖片.BYTE[]和base64string的轉換方法
下面小編就為大家?guī)硪黄狢#中圖片.BYTE[]和base64string的轉換方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-02-02C# 對PDF文檔加密、解密(基于Spire.Cloud.SDK for .NET)
這篇文章主要介紹了C# 基于Spire.Cloud.SDK for .NET對PDF文檔進行加密解密,文中講解非常細致,幫助大家更好的理解和學習,感興趣的朋友可以了解下2020-07-07C#實現(xiàn)的簡單整數(shù)四則運算計算器功能示例
這篇文章主要介紹了C#實現(xiàn)的簡單整數(shù)四則運算計算器功能,涉及C#界面布局、事件響應及數(shù)值運算等相關操作技巧,需要的朋友可以參考下2017-09-09