abarnybox
abarnybox

Reputation: 139

How to check a user ends connection unexpectedly

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

Upvotes: 1

Views: 46

Answers (1)

Gren
Gren

Reputation: 1854

  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;
    }
    

Upvotes: 2

Related Questions