2

I've been trying to do communication from another language to Java, but when I try read data from DataInputStream in a while loop...

static String getData(DataInputStream stream){

    int charbyte;
    StringBuilder strbuilder = new StringBuilder();
    try {
        while ((charbyte = stream.read()) != -1){
            strbuilder.append(Character.toChars(charbyte));
        }
        stream.close();

        return new String(strbuilder);

    } catch (Exception e) {
        return null;
    }
}

The problem is stream.read() is not returning -1 because it just keeps waiting for new data to be sent. How can I just get the data that was just sent?

user3818650
  • 581
  • 1
  • 7
  • 19

1 Answers1

2

The method never returns because the while loop never ends, and this is caused by the connection or the DataInputStream remaining open.

To send a variable number of bytes over a network connection where the reader reads a stream of characters you have three options:

  1. Send the number of bytes to follow, as an int in network order, followed by as many bytes.
  2. If the bytes are printable characters, send a null byte to indicate the end.
  3. Close the stream after sending the bytes.

For #1, change the loop to

try {
    int count = stream.readInt();
    for( int i = 0; i < count; ++i ){
        strbuilder.append(Character.toChars(stream.read()));
    }
    return strbuilder.toString();
}

For #2, use

try {
    while ((charbyte = stream.read()) != 0){
        strbuilder.append(Character.toChars(charbyte));
    }
    return strbuilder.toString();
}

The code you have now is for #3.

laune
  • 31,114
  • 3
  • 29
  • 42