[英]Socket Inputstream doesn't return -1 at the end of stream
這是發生問題的代碼片段:
public static byte[] copyLargeExt(InputStream input) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024*8];
int n = 0;
while(-1 != (n = input.read(buffer))) {
baos.write(buffer, 0, n);
// i just append this pattern ({###END###}) to force the break
/*if(baos.toString(UTF8.name()).endsWith("{###END###}")) {
break;
}*/
}
return baos.toByteArray();
}
有人能幫我嗎?
問題中的代碼讀取到套接字流的末尾。 如果該方法是阻塞的並且在讀取調用中,那么這只能意味着另一端尚未關閉其相應的輸出流。
你有兩個選擇:
更改另一端以關閉其輸出流,以便此代碼將看到EOF。
更改“協議”,以便此代碼知道要期望的數據字節數...並准確讀取該字節數。
在Java中。
如果Server只有Socket.close()
而沒有OutputStream.close()
,那么Client的InputStream.read()
將不會返回-1
。
相反,客戶端的InputStream.read()
將阻塞直到超時。 所以Server上的最佳實踐是:
OutputStream.close();
InputStream.close();
Socket.close();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.