如何设置一个TcpClient的超时

如何设置一个TcpClient的超时

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

问题描述

我有我使用将数据发送到一个监听远程计算机上的TcpClient。远程计算机有时会在时而关闭。正因为如此,所述的TcpClient将无法经常连接。我想TcpClient的一秒钟后超时,所以它并不需要太多的时间,当它不能连接到远程计算机。目前,我用这个code代表的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?

推荐答案

您需要使用异步 的TcpClient 的方法,而不是试图连接同步,这是构造做什么。事情是这样的:

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的超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 01:46