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

          主站蜘蛛池模板: 东乌珠穆沁旗| 桃江县| 商丘市| 石狮市| 桃园县| 安陆市| 陇西县| 陈巴尔虎旗| 五台县| 鸡西市| 竹北市| 贡嘎县| 城口县| 滕州市| 平定县| 铜川市| 乐安县| 满洲里市| 商南县| 巨野县| 杭锦旗| 江安县| 榆社县| 临澧县| 堆龙德庆县| 安义县| 马关县| 城步| 永和县| 蓝山县| 青神县| 康乐县| 广宗县| 汽车| 玛纳斯县| 鄂温| 镇雄县| 永兴县| 沛县| 米脂县| 荔浦县|