java - BufferedReader readLine detect closed socket and use .ready() -


server snippet:

reader = new bufferedreader(new inputstreamreader(new bufferedinputstream(connection.getinputstream()))); if (reader.ready()) {     result = reader.readline();     if (result == null) {          quit(); // handle closing socket     } else {          // process result     } } 

client snippet:

bufferedoutputstream os = new bufferedoutputstream(connection.getoutputstream()); outputstreamwriter osw = new outputstreamwriter(os, "us-ascii"); osw.write("hello\n"); osw.flush(); 

the problem:

when client writes server gets read correctly when client closes it's socket (for example force quitting program), reader.readline() should output null, because of if (reader.ready()) { null result never reach quit(). if leave away if (reader.ready()) {, server can't read data.

how fix this?

edit: can't use while ((result = reader.readline()) != null) { because need run more code after this:

while (running) {   try {     reader = new bufferedreader(new inputstreamreader(new bufferedinputstream(connection.getinputstream())));     if (reader.ready()) {       result = reader.readline();       if (result == null) quit();       else // process result     }     catch (exception e) { ... }      // more code   } } 

just remove ready() test. simple that. ready() not test end of stream. readline() block while there no data.

and must create bufferedreader once, outside read loop. otherwise lose data.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -