我有一个TcpClient,用于将数据发送到远程计算机上的侦听器。远程计算机有时会打开,有时会关闭。因此,TcpClient将经常无法连接。我希望TcpClient一秒钟后超时,因此当它无法连接到远程计算机时不需要花费很多时间。当前,我将以下代码用于TcpClient:
try { TcpClient client = new TcpClient("remotehost", this.Port); client.SendTimeout = 1000; Byte[] data = System.Text.Encoding.Unicode.GetBytes(this.Message); NetworkStream stream = client.GetStream(); stream.Write(data, 0, data.Length); data = new Byte[512]; Int32 bytes = stream.Read(data, 0, data.Length); this.Response = System.Text.Encoding.Unicode.GetString(data, 0, bytes); stream.Close(); client.Close(); FireSentEvent(); //Notifies of success } catch (Exception ex) { FireFailedEvent(ex); //Notifies of failure }
这足以处理任务。如果可以,它将发送它;如果无法连接到远程计算机,它将捕获异常。但是,当它无法连接时,将花费10到15秒的时间引发异常。我需要约一秒钟的时间吗?我将如何更改超时时间?
您将需要使用async BeginConnect方法TcpClient而不是尝试同步连接,这是构造函数所做的。像这样:
BeginConnect
TcpClient
var client = new TcpClient(); var result = client.BeginConnect("remotehost", this.Port, null, null); var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1)); if (!success) { throw new Exception("Failed to connect."); } // we have connected client.EndConnect(result);