Reading all input from a socket continuously
Solution 1
Since your client should read multiple multiline responses from same connection and process the each block of response, this might be useful for your case :
BufferedReader input = new BufferedReader(new InputStreamReader(server.getInputStream()));
String line;
StringBuilder sb = new StringBuilder();
while ((line = input.readLine()) != null) {
if (line.equals("~~/START/~~"))
sb = new StringBuilder();
else if (line.equals("~~/END/~~")) {
doSthWithParagraph(sb.toString());
sb.delete(0, sb.length());
} else
sb.append(line);
}
You can use your own special string to recognize start and end of each message block.
Solution 2
I would not rely on readLine
for your main loop because readLine
relies on "future" data (CR, or LF, or CR+LF, and return null if end of stream has been reached). Because of this, if CR is not followed by an LF, the BufferedReader
gets stucked. This readLine
method is more appropriate for reading file content.
In your case, I would read one character at a time with
while ((myChar = input.read()) != -1) {
// processing here, storing information in a buffer and taking appropriate actions if
// A CR or LF is found
}
But even this behaviour is dubious because a Unicode char can be more than one byte, so the stream could be stuck if the first byte is sent and not the second. Are you sure your communication is Unicode? If not, an InputStream
would be more appropriate than a Reader
.
Ree
Updated on June 04, 2022Comments
-
Ree almost 2 years
I'm writing a simple Java client/server application for my own use. It should allow clients to send single line text messages and read multiline responses. This kind of communication should be repeatable many times using the same connection.
This is what I have in the client for reading responses:
BufferedReader input = new BufferedReader(new InputStreamReader(server.getInputStream())); String line; while ((line = input.readLine()) != null) { // processing here }
The problem with this is that readLine() blocks once the server sends the first response back and the client cannot send new messages because of that. This is understandable. A naive workaround could be making the server signal the end of its output by sending some kind of a known special string value which the client would then recognize and end the reading loop. However, is there a better solution to this problem?