Вопрос

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?

Это было полезно?

Решение

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

Другие советы

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); 
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top