The easiest solution is to read the message character by character, but the main problem here is to find out when the message will be completed. In a line-oriented protocol, this is simple, the new line that was sent is the โdelimiterโ between the messages. Without this, two situations are possible when this problem is easily solved:
Case 1: a message always has a fixed character at the end that cannot happen in the message
// let pretend ! is the end of message marker final char endMarker = '!'; // or of course StringBuffer if you need to be treadsafe StringBuilder messageBuffer = new StringBuilder(); // reads to the end of the stream or till end of message while((value = br.read()) != -1) { char c = (char)value; // end? jump out if (c == endMarker) { break; } // else, add to buffer messageBuffer.append(c); } // message is complete! String message = messageBuffer.toString();
Case 2: The message has a fixed length
// let pretend message is always 80 long int messageLength = 80; StringBuilder messageBuffer = new StringBuilder(); int charactersRead = 0; // reads to the end of the stream or till end of message while((value = br.read()) != -1) { char c = (char)value; // end? jump out if (++charactersRead >= messageLength) { break; } // else, add to buffer messageBuffer.append(c); } // message is complete! String message = messageBuffer.toString();
In both cases, you will need to add code to verify the correctness of what you received, you may have received EOF while reading.
If there is no obvious message separator, and the message has a variable length, it will be much more complicated.
source share