Omar Kooheji
Omar Kooheji

Reputation: 55790

Will setting a timeout on a socket work if you are reading a full line using a buffered reader?

I'm writing a socket client that sends a line down a socket connection and then waits for up to 45 seconds for a line back from the server.

I'm using a buffered reader like so:

Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
            socket = new Socket(host, 800);
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(
                                        socket.getInputStream()));
} catch (UnknownHostException e) {
            listener.failedToConnectToHost(e);
            return;
} catch (IOException e) {
            listener.failedToConnectToHost(e);
        return;
}

        BufferedReader stdIn = new BufferedReader(
                new InputStreamReader(System.in));
        out.println("message");
try {
        String response = in.readLine();
        listener.responseRecived(response);
        return;
} catch (IOException e) {
        listener.errorReadingResponse(e);
        return;
}

If I add the following line (Or something like it)

socket.setSoTimeout(45000);

What will happen after 45 seconds assuming that nothing has come through from the other end?

I assume I'll be catching an interrupted exception but I'm sure?

Will this even work? The docs for setSOTImeOut() imply that it's socket.read() that will timeout, I assume that the buffered reader is calling this somewhere down the stack, but assumption is the mother of all screw ups, so I just wanted to check.

Upvotes: 4

Views: 1067

Answers (2)

Omar Kooheji
Omar Kooheji

Reputation: 55790

Apparently it does work and you get a SocketTimeoutException.

Upvotes: 0

Sibbo
Sibbo

Reputation: 3914

The BufferedReader.readLine() method will throw a SocketTimeoutException after 45 seconds.

Upvotes: 3

Related Questions