我有一个 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
}
这足以处理任务。如果可以,它会发送它,如果无法连接到远程计算机,则会捕获异常。但是,当它无法连接时,需要十到十五秒才能抛出异常。我需要它在大约一秒钟内超时吗?我将如何更改超时时间?
最佳答案
从 .NET 4.5 开始,TcpClient 有一个很酷的 ConnectAsync我们可以像这样使用的方法,所以现在很简单:
var client = new TcpClient();
if (!client.ConnectAsync("remotehost", remotePort).Wait(1000))
{
// connection failure
}
关于c# - 如何设置 TcpClient 的超时时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22504962/