http是無狀態(tài)的連接,不像socket可以有timeout的異常,因此在判斷超時(shí)上一直比較困擾.
這段時(shí)間做j2me的一個(gè)小游戲.用到了http連接,學(xué)習(xí)了論壇上說的一種方法.
"聲明一個(gè)boolean公共變量,表明當(dāng)前httpconnection是否得到服務(wù)器回應(yīng)。
你的連接線程中在連接之前置這個(gè)變量為false;
另起一個(gè)監(jiān)視線程,拿到那個(gè)HttpConnection的連接對(duì)象,并循環(huán)監(jiān)視這個(gè)boolean公共變量。如果指定時(shí)間內(nèi)(20秒后)你的boolean公共變量還是false,那么就主動(dòng)置httpconnection=null。這樣,那邊連接線程就會(huì)拋出異常退出來。"
寫了Timer類來實(shí)現(xiàn).(學(xué)習(xí)國外一個(gè)網(wǎng)站上的寫法)
class Timer extends Thread {
??/** 每個(gè)多少毫秒檢測(cè)一次 */
??protected int m_rate = 100;
??/** 超時(shí)時(shí)間長度毫秒計(jì)算 */
??private int m_length;
??/** 已經(jīng)運(yùn)行的時(shí)間 */
??private int m_elapsed;
??/**
?? * 構(gòu)造函數(shù)
?? *
?? * @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;
??}
??/**
?? * 重新計(jì)時(shí)
?? *
?? */
??public synchronized void reset() {
???m_elapsed = 0;
???System.out.println("reset timer");
??}
??/**
?? * 故意設(shè)置為超時(shí),可以在服務(wù)器有返回,但是錯(cuò)誤返回的時(shí)候直接調(diào)用這個(gè),當(dāng)成超時(shí)處理
?? *
?? */
??public synchronized void setTimeOut()
??{
???m_elapsed = m_length+1;
??}
??/**
?? ?*/
??public void run() {
???// 循環(huán)
???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;
?????}
????}
???}
??}
??/**
?? * 超時(shí)時(shí)候的處理
?? *
?? */
??public void timeout() {
??????httpConnection = null;
??????System.out.println("conn time > " + TIME_OUT + " ms");
????}
?}
不知道大家有沒有更好的方法
望回復(fù)賜教.