Sockets里面的Connect連接方法,沒有對連接超時的處理,系統默認20-30秒,等待時間長。所有直接用timer來實現,沒有連接上,直接tcpclitnet.close來關閉掉。
using System.Net.Sockets;
public static Socket tcpClient;
可以用計時器timer來實現,
public void Connect() { try { tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress iPAddress = IPAddress.Parse(IP); EndPoint endPoint = new IPEndPoint(iPAddress, port); RunFlag = false; // tcpClient.SendTimeout = 1000; timer.Interval = 1000; timer.Elapsed += MonitorTCP; if (!tcpClient.Connected) { lock (Obj) { timer.Start(); tcpClient.Connect(endPoint); RunFlag = true; // SendMsg("abc"); } } } catch { tcpClient.Close(); RunFlag = false; RightReciver = "vision連接失敗\r\n檢查IP與端口配置"; MessageBox.Show(RightReciver); } } public void MonitorTCP(object sender, System.Timers.ElapsedEventArgs e) { if (!tcpClient.Connected) { tcpClient.Close(); } // tcpClient.Disconnect(true); timer.Stop(); }