The following code should detect that there are no more bytes to be read. However it simply hangs until client connection is closed.
Server
//...
StringBuilder builder = new StringBuilder(128);
byte[] buffer = new byte[1024];
int length = 0;
while ((length = socket.getInputStream().read(buffer)) != -1) {
System.out.println(length);
builder.append(new String(buffer));
System.out.println(builder.toString());
}
Client
//...
OutputStream stream = clientSocket.getOutputStream();
stream.write("LIST".getBytes());
stream.flush();
The API and the previous answer on such question states that -1 should mean that there are no characters to be read, however this loop writes:
4
LIST
hangs for 20 seconds until client closes socket and picks up -1 to terminate loop.
How could i properly detect that there are no more characters in the stream ?
Connection should remain open after this.
I could send number of bytes in advance or special character, but is it possible to detect that there is nothing to be read any longer even if connection is still active.