Read all input from socket continuously

I am writing a simple Java application / Java server for my own use. It should allow clients to send single-line text messages and read multi-line responses. Such communication should be repeated many times using the same connection.

This is what I have in the client to read the answers:

BufferedReader input = new BufferedReader(new InputStreamReader(server.getInputStream())); String line; while ((line = input.readLine()) != null) { // processing here } 

The problem is that readLine () is blocked as soon as the server sends the first response, and the client cannot send new messages because of this. It's clear. A naive workaround may cause the server to signal completion of its output by sending some known special string value, which the client then recognizes and completes the read cycle. However, is there a better solution to this problem?

+4
source share
2 answers

Since your client should read multiple multi-line responses from the same connection and process each response block, this may 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 line to recognize the beginning and end of each message block.

+4
source

I would not rely on readLine for your main loop, because readLine relies on "future" data (CR, or LF, or CR + LF, and returns null if the end of the stream is reached). Because of this, if CR is not followed by LF, the BufferedReader gets stuck. This readLine method is more suitable for reading the contents of a file.

In your case, I will 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 behavior is doubtful, because the Unicode char can be more than one byte, so the stream can get stuck if the first byte is sent, and not the second. Are you sure your message is Unicode? If not, an InputStream would be more appropriate than a Reader .

+1
source

Source: https://habr.com/ru/post/1385487/


All Articles