1

I can't figure out why this wouldn't work:

private String clientInput() { String temp = ""; try { temp = in.readLine().trim(); if (temp == null) { out.println("4"); out.flush(); } } catch (IOException ioe) { out.println("6"); out.flush(); } return temp; } 

At the moment I have that method which should read input from a 'client' socket, 'in' is a bufferedReader, 'out' is a printwriter. I am supposed to make sure the program is robust enough to handle if the user ends the session unexpectedly. So when waiting for the user to input, I figured if they ended the session the input would end up being null. (is that right?) so I have a test class that sends the following data across:

String[] title = {"a","b","c","","e","f",null}; 

just to test that it would catch the null value...but it doesn't.

Just for reference the line that sends the values across is in a loop:

out.println(title[i]); out.flush(); 

Have I got the wrong idea? or am I just doing something wrong?

thanks abarnybox

3
  • It appears to be a good logical question. Commented Dec 6, 2014 at 11:09
  • 1
    Within the server class, while it is waiting for a readLine() to come in, if the user ends the connection then it would read in a null value wouldn't it?...or would it?... so I'm just sending null across to emulate that Commented Dec 6, 2014 at 11:36
  • Got your answer---Check this answer--->stackoverflow.com/questions/27331263/… Commented Dec 6, 2014 at 11:48

1 Answer 1

2
  1. readLine() blocks until a line has been completely read or the socket is closed or timeout occurs.
    If the socket has been closed by the sender, the method returns null. You do not need to send a null value.
    Sending null is impossible anyway, null is nothing and you cannot send nothing, right?
    (If you try to send the null in the String array, you pass in fact ""+null = "null" to the println method
    and your client receive the string "null\n".)

  2. Place your null check before trim. Otherwise you got a NullPointerException when the stream ends.

    private String clientInput() { String temp = ""; try { temp = in.readLine(); if (temp == null) { out.println("4"); out.flush(); } else { temp = temp.trim(); } } catch (IOException ioe) { out.println("6"); out.flush(); } return temp; } 
Sign up to request clarification or add additional context in comments.

2 Comments

If you have indents via numbered or bullet points you have to ident code after it twice.
thanks, you're right. And I was thinking it might result in a null pointer. I was just trying to test that it caught null that's why I was trying to send it across. But got it working now so thanks :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.