在C#中带连接超时功能的TcpClient类

关于TcpClient 类在C#中对于操作TCP connection是非常方便的,非常地好!

但是有一点就是,这个类对于CONNECT操作没有设置超时!

系统默认的是60秒的超时,这明显过于地长。

我们可以重新去用Thread的join这个带参数的线程,来解决这个问题,下面的这个类就是但连接超时参数的TCPCliento类

the TcpClientWithTimeout.cs class:

using System;
using System.Net.Sockets;
using System.Threading;

/// <summary>
/// TcpClientWithTimeout 用来设置一个带连接超时功能的类
/// 使用者可以设置毫秒级的等待超时时间 (1000=1second)
/// 例如:
/// TcpClient connection = new TcpClientWithTimeout('127.0.0.1',80,1000).Connect();
/// </summary>
public class TcpClientWithTimeout
{
  protected string _hostname;
  protected int _port;
  protected int _timeout_milliseconds;
  protected TcpClient connection;
  protected bool connected;
  protected Exception exception;

  public TcpClientWithTimeout(string hostname,int port,int timeout_milliseconds)
  {
    _hostname = hostname;
    _port = port;
    _timeout_milliseconds = timeout_milliseconds;
  }
  public TcpClient Connect()
  {
    // kick off the thread that tries to connect
    connected = false;
    exception = null;
    Thread thread = new Thread(new ThreadStart(BeginConnect));
    thread.IsBackground = true; // 作为后台线程处理
    // 不会占用机器太长的时间
    thread.Start();

    // 等待如下的时间
    thread.Join(_timeout_milliseconds);

    if (connected == true)
    {
      // 如果成功就返回TcpClient对象
      thread.Abort();
      return connection;
    }
    if (exception != null)
    {
      // 如果失败就抛出错误
      thread.Abort();
      throw exception;
    }
    else
    {
      // 同样地抛出错误
      thread.Abort();
      string message = string.Format("TcpClient connection to {0}:{1} timed out",
        _hostname, _port);
      throw new TimeoutException(message);
    }
  }
  protected void BeginConnect()
  {
    try
    {
      connection = new TcpClient(_hostname, _port);
      // 标记成功,返回调用者
      connected = true;
    }
    catch (Exception ex)
    {
      // 标记失败
      exception = ex;
    }
  }
}

下面的这个例子就是如何利用5秒的超时,去连接一个网站发送10字节的数据,并且接收10字节的数据。

// connect with a 5 second timeout on the connection
TcpClient connection = new TcpClientWithTimeout("www.google.com", 80, 5000).Connect();
NetworkStream stream = connection.GetStream();

// Send 10 bytes
byte[] to_send = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xa};
stream.Write(to_send, 0, to_send.Length);

// Receive 10 bytes
byte[] readbuf = new byte[10]; // you must allocate space first
stream.ReadTimeout = 10000; // 10 second timeout on the read
stream.Read(readbuf, 0, 10); // read

// Disconnect nicely
stream.Close();      // workaround for a .net bug: http://support.microsoft.com/kb/821625
connection.Close();
C#中,使用TcpClient连接网络时,可以通过设置TcpClient的Socket属性来配置连接超时连接超时通常用于指定在尝试连接到远程主机时允许的等待时间。如果在该时间范围内无法建立连接,则会抛出一个异常。以下是如何设置连接超时的步骤: 1. 创建TcpClient实例。 2. 获取TcpClient关联的Socket对象。 3. 使用Socket对象的`ConnectTimeout`属性来设置超时时间(单位为毫秒)。 4. 调用TcpClient的`Connect`方法尝试连接到远程主机。 请注意,由于Socket的`Connect`方法是同步的,所以当超时发生时,它会抛出一个`SocketException`异常。为了避免阻塞主线程,建议在后台线程中执行连接操作。 示例代码如下: ```csharp using System; using System.Net.Sockets; using System.Threading; public class TcpClientExample { public void ConnectToServer(string host, int port, int timeout) { TcpClient client = new TcpClient(); try { // 设置超时时间 client.Client.ReceiveTimeout = timeout; client.Client.SendTimeout = timeout; // 尝试连接到服务器 client.Connect(host, port); // 连接成功后的操作 Console.WriteLine("连接成功!"); // ... 进行数据交互等操作 ... } catch (SocketException ex) { // 处理连接超时连接错误 Console.WriteLine("连接服务器失败: " + ex.Message); } finally { client.Close(); } } } class Program { static void Main() { TcpClientExample example = new TcpClientExample(); // 假设连接超时设置为5000毫秒(即5秒) example.ConnectToServer("127.0.0.1", 12345, 5000); } } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值