[英]How to read from byte stream in Java (PHP/Java socket communication)
[英]Java: read a stream of byte from a socket
我正在設置一個軟件,該軟件以字節 [] 發送消息並接收字節流。 示例,發送數組
byte[] replayStatuse = new byte[] { 0x55, (byte) 0xAA, 0x0B, 0x00, 0x0A,
0x1C, 0x03, 0x41, 0x01, 0x00 }
我收到類似的東西。 我使用 PacketSender 進行了測試,當我詢問狀態時,我可以看到十六進制的答案。 我正在使用
InputStream socketInputStream = socket.getInputStream();
我已經嘗試了在堆棧和其他論壇上找到的各種方法,但沒有用。 像這樣的方法:
int read;
while((read = socketInputStream.read(buffer)) != -1)
{
String output = new String(buffer, 0, read);
System.out.print(output);
System.out.flush();
}
我嘗試使用 char、byte 或其他格式的 int read,但沒有使用。 在我的控制台中,它打印出奇怪的字符 (U)
我正在使用:
InputStream socketInputStream = socket.getInputStream();
socketInputStream.read();
我希望得到一個字節 [] 並能夠使用該函數讀取:
System.out.println(Arrays.toString(byteArray));
所以我可以處理各種情況並在需要時轉換為字符串或十六進制謝謝大家
字符“U”並不奇怪,它是十六進制值 0x55 的 ASCII 字符(即與您在測試數組中的第一個值相同)。 數組中接下來的幾個值可能會丟棄打印語句。 我建議檢查/顯示“緩沖區”的長度,以便您知道數組中放入了多少字節。
我不確定我是否完全理解你的問題,但讓我們試試
從一開始你就有一個字節來源,我假設大小是未知的。
byte[] buffer = new byte[4096]; //I assume you have something like this
//Lets use this to accumulate all the bytes from the inputstream
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
int read;
while((read = socketInputStream.read(buffer)) != -1)
{
byteStream.write(buffer, 0, read); //accumulates all bytes
}
byteStream.flush(); //writes out any buffered byte
byte[] allBytesRead = byteStream.toByteArray(); //All the bytes read in an array
這是發送的所有字節。 假設你想以十六進制打印每個字節
for(byte b : allBytesRead) {
//might not be a good ideia if its something big.
//build a string with a StringBuilder instead.
System.out.println(String.format("%02X", b));
}
現在由您決定如何處理這些字節。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.