判斷Socket是否連接上,需要通過發包來確認。 之前確認都是調用調用socket的connected屬性,然而該屬性是上次的連接是否成功的結果,不及時。 // 檢查一個Socket是否可連接 private bool IsSocketConnected(Socket client) { bool blockingState = client.Blocking; try { byte[] tmp = new byte[1]; client.Blocking = false; client.Send(tmp, 0, 0); return true; } catch (SocketException e) { // 產生 10035 == WSAEWOULDBLOCK 錯誤,說明被阻止了,但是還是連接的 if (e.NativeErrorCode.Equals(10035)) return false; else return true; } finally { client.Blocking = blockingState; // 恢復狀態 } }
C#客戶端連接服務器前先判斷服務器連接是否正常 #region 采用Socket方式,測試服務器連接 /// <summary> /// 采用Socket方式,測試服務器連接 /// </summary> /// <param name="host">服務器主機名或IP</param> /// <param name="port">端口號</param> /// <param name="millisecondsTimeout">等待時間:毫秒</param> /// <returns></returns> public static bool TestConnection(string host,int port,int millisecondsTimeout) { int millisecondsTimeout = 5;//等待時間 TcpClient client = new TcpClient(); try { var ar = client.BeginConnect(host, port, null, null); ar.AsyncWaitHandle.WaitOne(millisecondsTimeout); return client.Connected; } catch (Exception e) { throw e; } finally { client.Close(); } } #endregion
https://www.cnblogs.com/lonelyxmas/p/10878856.html