C# 给TcpClient的Connect方法设置超时时间 TimeOut

.Net 4.5的写法

try
{
// TcpClient client = new TcpClient(textBox_ip.Text.Trim(), Convert.ToInt32(textBox_port.Text.Trim()));

// TcpClient client = new TcpClient(ip.Trim(), Convert.ToInt32(port.Trim()));
TcpClient client = new TcpClient();

// client.Connect(ip.Trim(), Convert.ToInt32(port.Trim()));
if(!client.ConnectAsync(ip.Trim(),Convert.ToInt32(port.Trim())).Wait(5000))  //设置5秒超时
{
recv_text_data = "SocketException Connect Error!";
}

if (client.Connected)
{
NetworkStream serverStream = client.GetStream();

var newmsg = new SerMessage();

 
var client = new TcpClient();
if (!client.ConnectAsync("remotehost", remotePort).Wait(1000))
{
    // connection failure
}

4.5以前

复制代码
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);
复制代码
欢迎讨论,相互学习。 txwtech@163.com
原文地址:https://www.cnblogs.com/txwtech/p/14822110.html