/// <summary> /// 在指定时间内尝试连接指定主机上的指定端口。 (默认端口:80,默认链接超时:5000毫秒) /// </summary> /// <param name= "hostname ">要连接到的远程主机的 DNS 名。</param> /// <param name= "port ">要连接到的远程主机的端口号。 </param> /// <param name= "millisecondsTimeout ">要等待的毫秒数,或 -1 表示无限期等待。</param> /// <returns>已连接的一个 TcpClient 实例。</returns> public static TcpClient Connect(string hostname, int?port, int?millisecondsTimeout) { ConnectorState cs = new ConnectorState(); cs.Hostname = hostname; cs.Port = port ?? 80; ThreadPool.QueueUserWorkItem(new WaitCallback(ConnectThreaded), cs); if (cs.Completed.WaitOne(millisecondsTimeout ?? 5000, false)) { if (cs.TcpClient != null) { return(cs.TcpClient); } return(null); //throw cs.Exception; } else { cs.Abort(); return(null); //throw new SocketException(11001); // cannot connect } }
/// <summary> /// 在指定时间内尝试连接指定主机上的指定端口。 (默认端口:80,默认链接超时:5000毫秒) /// </summary> /// <param name= "hostname ">要连接到的远程主机的 DNS 名。</param> /// <param name= "port ">要连接到的远程主机的端口号。 </param> /// <param name= "millisecondsTimeout ">要等待的毫秒数,或 -1 表示无限期等待。</param> /// <returns>已连接的一个 TcpClient 实例。</returns> public static TcpClient Connect(string hostname, int? port, int? millisecondsTimeout) { ConnectorState cs = new ConnectorState(); cs.Hostname = hostname; cs.Port = port ?? 80; ThreadPool.QueueUserWorkItem(new WaitCallback(ConnectThreaded), cs); if (cs.Completed.WaitOne(millisecondsTimeout ?? 5000, false)) { if (cs.TcpClient != null) return cs.TcpClient; return null; //throw cs.Exception; } else { cs.Abort(); return null; //throw new SocketException(11001); // cannot connect } }