簡體   English   中英

Java Socket InputStream read()總是在結束之前返回-1

[英]Java Socket InputStream read() returns -1 always, just before end

我寫下載應用程序。 我想只使用java Socket來請求文件。 所以我在我的套接字中寫作HTTP協議規則。 我的應用程序創建一個連接,讀取標題后,使用我的socket的InputStreamread()方法。 一切順利。 有時連接可能會丟失。 但是我存儲了我正在讀取的字節,所以它再次創建了一個帶有HTTP Ranged GET的新Socket並繼續其工作。 但是當下載即將完成時,我的意思是當剩余少於10 KB時,所有連接都將丟失,並且它(按計划)再次嘗試打開新的Socket並繼續其工作。 它完全讀取響應的頭部但在讀取body的任何字節之前, read()方法返回-1並且再次和它再次嘗試打開一個新的Socket並read()剩余的字節,但問題仍然存在。 關鍵是每次都可以完全讀取響應頭。 我看到響應頭的Content-Length:字段正好是文件的剩余字節。 我忘了提到:我的代碼有問題,因為我從許多服務器檢查了很多文件,結果是一樣的。 這是代碼:

// Some fields:
int state;
long start, current, end;

// in a thread:
while (state != FINISHED) {
    if (state == DOWNLOADING) {
        try {
            // fill a new socket with Ranged GET [current, end]
            Socket s = initConnection();
            InputStream in = s.getInputStream();
            int readNo = 0;
            FileOutputStream out = getTempFile();
            byte[] buffer = new byte[1024];
            // read response headers successfully and prints them, request range is OK. a sample of its print is at the end of page
            readHeaders(in);
            while (state == DOWNLOADING && (readNo = in.read(buffer)) != -1) {                      
                current += readNo;
                out.write(buffer, 0, readNo);
            }
            if (readNo == -1) {
                // at nearly end of download always print this and values never changes, where usually they have 3000 byte difference
                System.out.println("**************> (" + current + " - " + end + ")");
            }
            if (currentByte == endByte) {
                state = FINISHED;
                //mergeParts();
                // code never reaches here
                dlInfo.checkAllPartsFinished();
            }
            out.flush();
            out.close();
            s.close();
        } catch (Exception e) {
            e.printStackTrace();
            state = ERROR;
            error = e.getMessage();
            errorRetry++;
        }
    } else if (state == PAUSED) {
        // ...
    } else ...
    }
}

文件末尾的響應頭示例,其中沒有任何更改:

HTTP/1.1 206 Partial Content
Date: Mon, 21 May 2012 14:34:27 GMT
Server: Apache
Last-Modified: Sat, 21 Apr 2012 02:16:20 GMT
ETag: "4006d32e-f691e0-4be26fda00500"
Accept-Ranges: bytes
Content-Length: 7859
Content-Range: bytes 2012041-2019899/16159200
Connection: close
Content-Type: application/octet-stream

**************> (2012041 - 2019899)

我不知道問題是什么,但不論它是什么,它幾乎發生在流的末尾。 花了好幾個小時后,我完全糊塗了。 我將不勝感激任何幫助!

感謝名單

您是否在readHeaders()方法的InputStream之上分層緩沖讀取器/流? 我的猜測是你正在這樣做,並且這個緩沖流正在讀取比你預期更多的InputStream(因為它是緩沖的 )。 readHeaders()方法返回時,這些字節將丟失。

更新:

剛剛看到你的最后評論。 這正是你的問題。 BufferedReader正在消耗部分正文字節。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM