Reading Socket InputStream in a loop when writing byte arrays

This is what you usually do when sending text data

// Receiver code
while (mRun && (response = in.readLine()) != null && socket.isConnected()) {
    // Do stuff                 
}

// Sender code
printWriter.println(mMessage);
printWriter.flush();

but when working with DataOutputStream#write(byte[]) to send byte[], how do you write a while loop to receive sent data.

All I have found is this, but it doesn't loop, so I'm guessing this will just run on the first sent message:

int length = in.readInt();
byte[] data = new byte[length];
in.readFully(data);

How can I achieve this?

PS: yep, I'm new to socket programming.

EDIT: I'm sending a byte array each 3 to 5 seconds. This is what I've got so far.

// In the client side, in order to send byte[]. This is executed each 3 seconds.
if(out != null) {
    try {
        out.writeInt(encrypted.length);
        out.write(encrypted);
        out.writeInt(0);
        out.flush();
        return true;

    } catch (IOException e) {
        e.printStackTrace();

        return false;
    }
}


 // In the serverside, in order to receive byte[] sent from client (also executed 3 to 5 seconds due to bytes being sent at said rate.  "client" being the Socket instance.
while(true && client.isConnected()) {

    byte[] data = null;

    while(true) {
        int length = in.readInt();
        if(length == 0)
            break;

        data = new byte[length];
        in.readFully(data);
    }

    if(data != null) {
        String response = new String(data);

        if(listener != null) {
            listener.onMessageReceived(response);
        }
    }
}
Jon Skeet
people
quotationmark

Assuming you're trying to handle a stream of messages, sounds like what you're missing is a way of specifying (in the stream) how big your messages are (or where they end).

I suggest you just write a prefix before each message, specifying the length:

output.writeInt(data.length);
output.write(data);

Then when reading:

while (true)
{
    int length = input.readInt();
    byte[] buffer = new byte[length];
    input.readFully(buffer, 0, length);
    // Process buffer
}

You'll also need to work out a way of detecting the end of input. DataInputStream doesn't have a clean way of detecting that as far as I can tell. There are various options - the simplest may well be to write out a message of length 0, and break out of the loop if you read a length of 0.

people

See more on this question at Stackoverflow