我正在從服務器流式傳輸文件,然後將其流式傳輸回套接字(基本上是流代理)。這被用來緩衝歌曲。所以一旦緩衝區已滿,在緩衝區清空之前不會再有數據從套接字讀取。但是,再次讀取數據時,InputStream將讀取X個字節,然後突然返回-1表示文件結束,否則表示文件結束。是否有超時發生?InputStream在文件結束前返回-1
下面是一些示例代碼:
InputStream data = realResponse.getEntity().getContent();
...some code...
int totalBytes = 0;
int count = 0;
// Start streaming content.
byte[] buff = new byte[1024 * 50];
while (isRunning && (readBytes = data.read(buff, 0, buff.length)) != -1) {
totalBytes += readBytes;
Log(count + ": buffer:" + buff + " readBytes:" + readBytes + " total:" + totalBytes);
client.getOutputStream().write(buff, 0, readBytes);
Log("Finished write");
count++;
}
日誌的一個例子是這樣的:
0: buffer:[email protected] readBytes: 16164 total: 16164
1: buffer:[email protected] readBytes: 16384 total: 32548
...
100: buffer:[email protected] readBytes: 16384 total: 1654564
<a long pause here>
100: buffer:[email protected] readBytes: 16384 total: 1670948
100: buffer:[email protected] readBytes: 16384 total: 1687332
-1 Received
任何幫助或建議,欣賞
上面的日誌似乎不符合代碼。日誌中沒有「完成寫入」消息,並且沒有記錄「-1已接收」的代碼。在'totalBytes'範圍內定義了'readBytes'? 'count'在哪裏設置? 'count'和'readBytes'之間有關係嗎? – 2011-05-11 02:48:33
爲了可讀性,我清理了一些日誌並取出了「完成的寫入」,但忘記將它從代碼中取出。 「-1已收到」在未顯示的日誌語句中。 readBytes,totalBytes和count都在範圍內。 count變量只是用於調試已經完成了多少次讀/寫操作。 – Nick 2011-05-11 14:17:29
那'isRunning'布爾檢查怎麼樣?這是一個多線程應用程序嗎?可以設置該標誌爲false? – amischiefr 2011-05-11 14:31:10