Reputation: 280168
I have a server that times out after 45 seconds if it hasn't received a full request and closes the connection. I connect to this server through a Socket
and write my request to the socket's OutputStream
.
Socket socket = new Socket("myhost", myPort);
PrintWriter out = new PrintWriter(socket.getOutputStream());
out.write(properRequestMessage);
out.flush();
I'm assuming here that my request is good (follows my protocol). The server is supposed to respond with a file. I try to read from the socket inputstream:
BufferedReader response = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String in;
while((in = response.readLine()) != null) {
System.out.println(in);
}
The readLine()
blocks here and I think it is because my server thinks my request isn't properly terminated and is therefore waiting for more.
Now, if 45 seconds pass and my server times out, will the readLine()
unblock or wait for some Socket
default timeout time?
Upvotes: 4
Views: 1778
Reputation: 16208
The readLine()
method will block until it receives an input or until the underlying socket read()
timeout ends.
You don't set the timeout on the read command but rather on the socket it self.
Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. With this option set to a non-zero timeout, a read() call on the InputStream associated with this Socket will block for only this amount of time. If the timeout expires, a java.net.SocketTimeoutException is raised, though the Socket is still valid. The option must be enabled prior to entering the blocking operation to have effect. The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.
What actually occurs also depends on what the server does, if it closes the socket correctly a IOException
should be thrown by readLine()
. If the connection isn't close it will wait for the socket to timeout.
Upvotes: 1
Reputation: 84239
If the server closes its end of the socket on that timeout, then readLine()
will return null
.
Upvotes: 1
Reputation: 533870
That depends on what the server does when it times out. If it closes the connection you will see that. If it just logs a message, you might not see anything.
There is no default read timeout. Your readLine() can wait forever.
Upvotes: 6