Search code examples
javasocketsinputstreambytearrayinputstream

Read Socket stream data and read first 2 bytes, find rest of message length


How to read first 2 bytes from input stream and convert 2 bytes data into actual int length value, then read and copy the rest of message into byte array. The rest of data array should be defined after reading first 2 bytes from the stream, does anyone know efficient logic?


Solution

  • Use a DataInputStream. Use the readUnsignedShort() method to return the length word, then the readFully() method to read the following data.