• 在C#中带连接超时功能的TcpClient类(翻译自MSDN论坛CMF)


    关于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();

  • 相关阅读:
    selenium 浏览器操作
    selenium 4.0新特性及新旧api对比
    Selenium123介绍
    selenium元素定位(三) css定位方法
    selenium 安装和启动
    Selenium元素定位(一)30+1+5种方式
    软件开发经验收集
    spring+hibernate架构中Dao访问数据库的几种方法
    某励志书4
    PHP的Foreach
  • 原文地址:https://www.cnblogs.com/dosboy/p/2200899.html
Copyright © 2020-2023  润新知