如何为TcpClient设置超时时间?

104

我有一个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
}

这对于处理任务来说已经足够好了。如果可以发送,则发送,如果无法连接到远程计算机,则捕获异常。然而,当它无法连接时,要抛出异常需要十到十五秒钟。我需要它在大约一秒钟内超时。我该如何更改超时时间?

11个回答

0

使用超时和取消令牌的ConnectAsync()方法(.NET 6)
对于我的目的(即检查连接性),有一个更简单的方法可行。

using var tcpClient = new TcpClient();
var connectTask = tcpClient.ConnectAsync(host, port, cancellationToken);
await connectTask.AsTask().WaitAsync(TimeSpan.FromSeconds(5), cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
// Use connected TcpClient here

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接