java http 链接超时判断(转)

 

 

"声明一个boolean公共变量,表明当前httpconnection是否得到服务器回应。

你的连接线程中在连接之前置这个变量为false;

另起一个监视线程,拿到那个HttpConnection的连接对象,并循环监视这个boolean公共变量。如果指定时间内(20秒后)你的boolean公共变量还是false,那么就主动置httpconnection=null。这样,那边连接线程就会抛出异常退出来。"

写了Timer类来实现.(学习国外一个网站上的写法)

class Timer extends Thread {
  /** 每个多少毫秒检测一次 */
  protected int m_rate = 100;

  /** 超时时间长度毫秒计算 */
  private int m_length;

  /** 已经运行的时间 */
  private int m_elapsed;

  /**
   * 构造函数
   * 
   * @param length
   *            Length of time before timeout occurs
   */
  public Timer(int length) {
   // Assign to member variable
   m_length = length;

   // Set time elapsed
   m_elapsed = 0;
  }
  /**
   * 重新计时
   *
   */

  public synchronized void reset() {
   m_elapsed = 0;
   System.out.println("reset timer");
  }
  /**
   * 故意设置为超时,可以在服务器有返回,但是错误返回的时候直接调用这个,当成超时处理
   *
   */
  public synchronized void setTimeOut()
  {
   m_elapsed = m_length+1;
  }

  /** 
    */
  public void run() {
   // 循环

   System.out.println("timer running");
   for (;;) {
    // Put the timer to sleep
    try {
     Thread.sleep(m_rate);
    } catch (InterruptedException ioe) {
     continue;
    }

    synchronized (this) {
     // Increment time remaining
     m_elapsed += m_rate;

     // Check to see if the time has been exceeded
     if (m_elapsed > m_length && !isConnActive) { //isConnActive 为全局变量
      // Trigger a timeout
      timeout();
      break;
     }
    }

   }
  }

  /**
   * 超时时候的处理
   *
   */
  public void timeout() {
      httpConnection = null;
      System.out.println("conn time > " + TIME_OUT + " ms");
    }
 }

posted @   wtx  阅读(4429)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述
点击右上角即可分享
微信分享提示