|
发表于 2018-8-3 16:10:50
|
显示全部楼层
TCP超时时间设置!
本class 来自网络,目前我正在使用!
使用方法 TimeOutSocket.Connect(IPPoint, SocketTimeout);
- class TimeOutTcpClient
- {
- private static bool IsConnectionSuccessful = false;
- private static Exception socketexception;
- private static ManualResetEvent TimeoutObject = new ManualResetEvent(false);
- public static TcpClient Connect(IPEndPoint remoteEndPoint, int timeoutMSec)
- {
- 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(timeoutMSec, false))
- {
- if (IsConnectionSuccessful)
- {
- return tcpclient;
- }
- else
- {
- throw socketexception;
- }
- }
- else
- {
- tcpclient.Close();
- throw new TimeoutException("Connection TimeOut");
- }
- }
- 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();
- }
- }
- }
- class TimeOutSocket
- {
- private static bool IsConnectionSuccessful = false;
- private static Exception socketexception;
- private static System.Threading.ManualResetEvent TimeoutObject = new System.Threading.ManualResetEvent(false);
- public static Socket Connect(IPEndPoint remoteEndPoint, int timeoutMSec)
- {
- TimeoutObject.Reset();
- socketexception = null;
- Socket socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- socketClient.BeginConnect(remoteEndPoint, new AsyncCallback(CallBackMethod), socketClient);
- if (TimeoutObject.WaitOne(timeoutMSec, false))
- {
- if (IsConnectionSuccessful)
- return socketClient;
- else
- throw socketexception;
- }
- else
- {
- socketClient.Close();
- throw new TimeoutException("Connection TimeOut ");
- }
- }
- private static void CallBackMethod(IAsyncResult asyncresult)
- {
- try
- {
- IsConnectionSuccessful = false;
- Socket socketClient = asyncresult.AsyncState as Socket;
- if (socketClient != null)
- {
- socketClient.EndConnect(asyncresult);
- IsConnectionSuccessful = true;
- }
- }
- catch (Exception ex)
- {
- IsConnectionSuccessful = false;
- socketexception = ex;
- }
- finally
- {
- TimeoutObject.Set();
- }
- }
- }
复制代码 |
|