Reputation: 157
I have a doubt on where to set the socket timeout within my code. What I am trying to achieve is that when the socket is created the timeout should be 10seconds. So I am setting it before the handshake. now the error that I see in the logs are of two kinds. 1) Connection Timeout Error and 2) Read timeout Error. So I was wondering if anyone could explain me more about where to set the timeouts. I have the following code:
try{
SSLSocketFactory factory=(SSLSocketFactory)SSLSocketFactory.getDefault();
socket = (SSLSocket)factory.createSocket(host,port);
socket.setSoTimeout(10000);
socket.startHandshake();
OutputStream socketOut =( socket.getOutputStream() );
String command = method+" "+path+" HTTP/1.0\n";
//command+="Host: "+host+"\nConnection: close\n";
if (data!=null) {
command+="Content-Length: " + data.length +"\n\n";
sendBytes.write(command.getBytes(),0,command.length());
sendBytes.write(data,0,data.length);
} else {
// if data == null then we are most likely doing a GET request
sendBytes.write(command.getBytes(),0,command.length());
}
sendBytes.write("\n".getBytes(),0,"\n".length());
temp = sendBytes.toByteArray();
socketOut.write(temp,0,temp.length);
socketOut.flush();
/* read response */
BufferedInputStream socketIn =
new BufferedInputStream( socket.getInputStream() );
byte[] inputData = new byte[READSIZE];
while ((bytesRead=socketIn.read(inputData,0,READSIZE)) > -1) {
receiveBytes.write(inputData,0,bytesRead);
}
result=receiveBytes.toByteArray();
//receiveBytes.close();
//sendBytes.close();
//socket.close();
} catch (Exception e) {
throw e;
}finally {
try { receiveBytes.close(); sendBytes.close(); socket.close(); } catch (Exception ee) {}
}
return result;
} // end submit
} // end class
Please let me know how can i get the timeout to atleast work . In the logs the errors are occuring at 18secs ( which should not be the case) instead of 10secs.
Thanks
Upvotes: 2
Views: 18047
Reputation: 39620
The problem is most likely that the timeout already occurs upon connection when creating your socket. Try instantiating an unconnected socket first with the no arguments factory method and then use Socket#connect with the timeout
option in addition to Socket#setSoTimeout
. The latter only kicks in for these operations
ServerSocket.accept()
SocketInputStream.read()
DatagramSocket.receive()
but does not handle timeouts during connection attempts.
See also the technical article for networking timeouts for more details.
Upvotes: 2