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