java中處理http連接超時.

          Posted on 2006-07-06 15:50 Hally 閱讀(4914) 評論(0)  編輯  收藏 所屬分類: 學習隨筆

          http是無狀態的連接,不像socket可以有timeout的異常,因此在判斷超時上一直比較困擾.

          這段時間做j2me的一個小游戲.用到了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");
          ????}
          ?}


          不知道大家有沒有更好的方法

          望回復賜教.

          posts - 43, comments - 200, trackbacks - 0, articles - 2

          Copyright © Hally

          主站蜘蛛池模板: 什邡市| 同江市| 高平市| 孝昌县| 义马市| 大兴区| 永康市| 洞口县| 开化县| 乐亭县| 荔浦县| 绍兴市| 繁昌县| 曲麻莱县| 壶关县| 乌兰察布市| 南汇区| 区。| 德清县| 盐池县| 长岭县| 南昌市| 石阡县| 青海省| 磐石市| 铜陵市| 顺昌县| 凭祥市| 革吉县| 若尔盖县| 渭源县| 中西区| 马尔康县| 大姚县| 宁陕县| 郴州市| 黄浦区| 桓仁| 武冈市| 台安县| 黄平县|