private static ManualResetEvent TimeoutObject = new ManualResetEvent(false); /// <summary> /// Socket鏈接請求 /// </summary> ///<param name="remoteEndPoint">網絡端點</param> ///<param name="timeoutMSec">超時時間</param> public static void Connect(IPEndPoint remoteEndPoint, int timeoutMSec) { TimeoutObject.Reset(); var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.BeginConnect(remoteEndPoint, CallBackMethod, socket); //阻塞當前線程 if (TimeoutObject.WaitOne(timeoutMSec, false)) { //MessageBox.Show("網絡正常"); Console.WriteLine("網絡正常"); } else { //MessageBox.Show("鏈接超時"); Console.WriteLine("鏈接超時"); } } //--異步回調方法 private static void CallBackMethod(IAsyncResult asyncresult) { //使阻塞的線程繼續 TimeoutObject.Set(); } private delegate string ConnectSocketDelegate(IPEndPoint ipep, Socket sock); private string ConnectSocket(IPEndPoint ipep, Socket sock) { string exmessage = ""; try { sock.Connect(ipep); } catch (System.Exception ex) { exmessage = ex.Message; } finally { } return exmessage; } static void Main(string[] args) { string domain = "rfid.belle.cn"; Tuple<bool, string> result = GetDomainIP(domain); if (result.Item1) { IPAddress ip = IPAddress.Parse(result.Item2); IPEndPoint ipep = new IPEndPoint(ip, 900);//IP和端口 Connect(ipep, 6000); } Console.ReadLine(); } private static Tuple<bool, string> GetDomainIP(string domain) { try { string Result = domain;//提取域名地址 IPHostEntry host = Dns.GetHostByName(Result);//域名解析的IP地址 IPAddress ip = host.AddressList[0]; string rIP = ip.ToString(); return Tuple.Create(true, rIP); } catch { return Tuple.Create(false, "請輸入正確的域名,或者您的電腦沒有聯互聯網"); } }