zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    springCloud、springBoot学习
    企业级应用和互联网应用的去区别
    软件工程 期末总结
    四则运算
    读后感
    软件工程自评
    wc
    自我介绍
    学习javaE的目标
    基于Caffe的DeepID2实现(中)
  • 原文地址:https://www.cnblogs.com/txwtech/p/14822110.html
Copyright © 2011-2022 走看看