如何设置 TcpClient 的超时时间? [英] How to set the timeout for a TcpClient?

查看:59
本文介绍了如何设置 TcpClient 的超时时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 TcpClient,用于将数据发送到远程计算机上的侦听器.远程计算机有时会打开有时会关闭.因此,TcpClient 将经常无法连接.我希望 TcpClient 在一秒后超时,因此当它无法连接到远程计算机时不会花费太多时间.目前,我将此代码用于 TcpClient:

I have a TcpClient which I use to send data to a listener on a remote computer. The remote computer will sometimes be on and sometimes off. Because of this, the TcpClient will fail to connect often. I want the TcpClient to timeout after one second, so it doesn't take much time when it can't connect to the remote computer. Currently, I use this code for the 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
}

这足以处理任务.如果可以,它会发送它,如果它无法连接到远程计算机,则捕获异常.但是,当它无法连接时,需要十到十五秒才能抛出异常.我需要它在一秒钟内超时吗?我将如何更改超时时间?

This works well enough for handling the task. It sends it if it can, and catches the exception if it can't connect to the remote computer. However, when it can't connect, it takes ten to fifteen seconds to throw the exception. I need it to time out in around one second? How would I change the time out time?

推荐答案

您需要使用异步 TcpClientBeginConnect 方法,而不是尝试同步连接,这是构造函数所做的.像这样:

You would need to use the async BeginConnect method of TcpClient instead of attempting to connect synchronously, which is what the constructor does. Something like this:

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);

这篇关于如何设置 TcpClient 的超时时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆