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);
復制代碼

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM