zoukankan      html  css  js  c++  java
  • 在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();

  • 相关阅读:
    电商概念
    Linux知识点(二)
    linux知识点
    笔记8月20日
    考勤运行提示‘Length of values (115) does not match length of index (116) >>> ’
    数据透视表+数据条
    CCRC软件开发评审-材料应该怎么准备
    python os.walk函数
    httprunner 断言报错 expect_value 和check_value类型不一致
    自动化-Yaml文件读取函数封装
  • 原文地址:https://www.cnblogs.com/dosboy/p/2200899.html
Copyright © 2011-2022 走看看