-1

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?

  • 1
    @ejp voting is anonymous, no explanation necessary. Asking for explanations is noise and to be deleted. – casperOne Apr 17 '13 at 01:07

2 Answers2

3

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

user207421
  • 305,947
  • 44
  • 307
  • 483
  • thank you very much for your all the encouragements. if I receive multiple messages from the input stream, don't I need to use while loop?? because continuously data flowing from the socket. – pradeekrathnayaka Apr 16 '13 at 03:06
  • That will only work if the size is at most (2^15)-1. readShort will return a negative number if the size is greater than Short.MAX_VALUE – DeltaLima Apr 16 '13 at 06:47
  • @pradeekrathnayaka Of course you need a loop. Each iteration should do the above. – user207421 Apr 16 '13 at 07:37
  • @EJP Thanks for that. I never noticed that readUnsignedShort method, always did the bitwise &0xFFFF masking to convert it. This is clearer for the reader. +1 – DeltaLima Apr 16 '13 at 09:47
1

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); 
}
nook
  • 2,378
  • 5
  • 34
  • 54