-
TcpClient 類別 : 建立TCP連接物件。
-
IPGlobalProperties.GetIPGlobalProperties()方法:傳回本機電腦上之網際網路通訊協定第 4 版 (IPv4) 和 IPv6 傳輸控制通訊協定 (TCP) 接聽程式的端點資訊。
-
TcpConnectionInformation類別:提供本機電腦上的傳輸控制通訊協定 (TCP) 連線資訊。
使用TcpClient類別建立Google Mail Server(端口465)的連線,設定為連線超過3秒鐘為逾時時間,並透過 IPGlobalProperties類別來篩選出目前所有的TCP連線。程式碼如下:
TcpClient client = new TcpClient();
bool result = client.ConnectAsync("smtp.gmail.com", 465).Wait(3000);
//以上兩行也可這樣寫
//TcpClient tc1 = new TcpClient();
//var connectResult = tc1.BeginConnect("smtp.gmail.com", 465, null, null);
//var success = connectResult.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(3));
try
{
IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
TcpConnectionInformation[] tcpConnections = ipProperties.GetActiveTcpConnections().Where(x => x.LocalEndPoint.Equals(client.Client.LocalEndPoint) && x.RemoteEndPoint.Equals(client.Client.RemoteEndPoint)).ToArray();
if (tcpConnections != null && tcpConnections.Length > 0)
{
TcpState stateOfConnection = tcpConnections.First().State;
if (stateOfConnection == TcpState.Established)
{
// Connection is OK
}
else
{
// No active tcp Connection to hostName:port
}
}
client.Close();
}
catch(Exception ex)
{
ex.ToString();
}
中斷點參考圖
參考來源:
https://oomake.com/question/261594