Use a DataInputStream.
Use the readUnsignedShort()
method to return the length word, then the readFully()
method to read the following data.
Read Socket stream data and read first 2 bytes, find rest of message length
-
04-04-2022 - |
Вопрос
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?
Решение
Другие советы
This creates a string from a byte array. Adapt as needed.
InputStream in;
try {
in = socket.getInputStream();
DataInputStream dis = new DataInputStream(in);
int len = dis.readInt();
byte[] data = new byte[len];
if (len > 0) {
dis.readFully(data);
}
String sReturn = new String(data);
}
Не связан с StackOverflow