简体   繁体   中英

Java: read a stream of byte from a socket

Im setting up a software that send a message in byte [] and receive a stream of byte. Example, send the array

byte[] replayStatuse = new byte[] { 0x55, (byte) 0xAA, 0x0B, 0x00, 0x0A, 
0x1C, 0x03, 0x41, 0x01, 0x00 }

and I receive something similar. I did the test using PacketSender and I can see the answer in Hex when I ask the status. Im using

InputStream socketInputStream = socket.getInputStream();

I already tried the various method I found here on stack and other forum but it didnt works. Methods like this:

int read;
while((read = socketInputStream.read(buffer)) != -1)
{
   String output = new String(buffer, 0, read);
   System.out.print(output);
   System.out.flush();
}

I tried to use int read of type char, byte or other format but nothing. In my console it prints strange char (U)

Im using:

InputStream socketInputStream = socket.getInputStream();
socketInputStream.read();

Im expecting to get a byte[] and be able to read with the function:

System.out.println(Arrays.toString(byteArray));

So I can then handle the various cases and transform if need to a String or HEX Thank you all

The character 'U' is not strange, it is the ASCII character for the hexadecimal value of 0x55 (ie the same as your first value in the test array). The next few values in the array may be throwing off the print statement. I recommend checking/displaying the length of 'buffer' so you know how many bytes were placed into the array.

I'm not sure I understand your problem completely but lets try

From the beginning you have a source of bytes, I will assume the size is unknown.

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

This is all the bytes that were sent. Say you want to print each byte in hex

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));
}

Now it's up to you how you will process these bytes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM