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");
    }
 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM