首先請原諒我,如果我誤認爲阻塞是如何工作的,我的理解阻塞會暫停線程直到它準備好,例如當讀取用戶輸入時,程序將等待直到用戶返回。DataInputStream讀取不阻止
我的問題是,而不是等待數據變得可用,它讀取值爲0的字節。有沒有辦法阻止,直到數據becoms可用?
readBytes方法在循環中調用。
public byte[] readBytes(){
try{
//read the head int that will be 4 bytes telling the number of bytes that follow containing data
byte[] rawLen = new byte[4];
socketReader.read(rawLen);
ByteBuffer bb = ByteBuffer.wrap(rawLen);
int len = bb.getInt();
byte[] data = new byte[len];
if (len > 0) {
socketReader.readFully(data);
}
return data;
} catch (Exception e){
e.printStackTrace();
logError("Failed to read data: " + socket.toString());
return null;
}
}
擴展'InputStream' **的流將''read''阻塞請參閱https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#read() 'readFully'也會阻止 - 也許服務器發送零。 –
你將不得不原諒我,因爲這是我第一次使用套接字。我曾嘗試使用以下內容作爲閱讀器,結果是相同的。 InputStream socketReaderStream = socket.getInputStream(); – user2131323
您對'read()'的使用可能不會讀取全部4個字節。你是否想在那裏使用'readFully()'來確保你讀取所有4個字節? read()的返回值是實際讀取的字節數。 – ck1