0
服務器發送了我一個int根據:如何用BufferedInputStream.read()獲取真正的字節順序?
DataOutputStream stdOut = new DataOutputStream(myServerSocket.getOutputStream());
stdOut.writeInt(1);
stdOut.flush();
我試圖從我的客戶端閱讀:
BufferedInputStream dIn = new BufferedInputStream(myClientSocket.getInputStream());
byte[] reception = new byte[4]; // writeInt() writes 4 bytes
int status = -1;
status = dIn.read(reception, 0, 4);
// status = 1
// (int) reception = 0
我在等待4個字節來計算髮送詮釋。 但是,它只是接收1個字節並在不等待剩餘字節的情況下處理它。 因爲我等待4個字節,我嘗試這樣做,則:
int count = 0;
while(count < 4) {
status = dIn.read(reception);
count += status;
System.out.println("Read: " + count);
}*/
我看到它讀取1個字節然後3個字節。
- Enventually,當我打印的HEX結果,我得到:00 00 01 00
- 它似乎什麼發送這樣的(按順序):00 00 00 01
- 而在兩個接收部分:00,然後00 00 01
- 其中儲存,如:00 00 01 00
這就是爲什麼我沒有得到我的INT 1
- 如果不等待4 字節,讀取的目的是什麼(字節,0,4)?
- 如何以真正的順序簡單地得到我的4個字節?
注:當客戶端使用DataInputStream類,一的readInt()工作正常...
我不知道我理解你的問題。如果DataInputStream具有您需要的行爲,然後使用它。 –
1. 4指定要傳輸的最大字節數,因爲它在Javadoc中清楚說明。 2.你的讀循環有一個錯誤,'readInt()'沒有。不清楚爲什麼你不使用有效的代碼,這與發送者是對稱的。 – EJP
我在這個論壇上看到BufferedInput/OutputStream更快。我想嘗試它來比較。 – Anduriel