public void CheckOpenPortByBeginConnect() { var port = ProcessingPort++; try { var timeout = 5000; var newClient = new TcpClient(); var state = new IsTcpPortOpen { MainClient = newClient, tcpOpen = true }; IAsyncResult ar = newClient.BeginConnect("trungtvq.ddns.net", port, AsyncCallback, state); if (ar.AsyncWaitHandle.WaitOne(timeout, false) == false || newClient.Connected == false) { //throw new Exception(); return; } OpenedPortList.Add(port); //System.Diagnostics.Debug.WriteLine("Open at" + port); } catch { System.Diagnostics.Debug.WriteLine("Close at" + port); } }
public TcpClient Connect(string hostName, int port, int timeout) { var newClient = new TcpClient(); var state = new IsTcpPortOpen { MainClient = newClient, tcpOpen = true }; IAsyncResult ar = newClient.BeginConnect(hostName, port, AsyncCallback, state); state.tcpOpen = ar.AsyncWaitHandle.WaitOne(timeout, false); if (state.tcpOpen == false || newClient.Connected == false) { System.Diagnostics.Debug.WriteLine("tao nem"); throw new Exception(); } return(newClient); }