SSL连接超时和读取超时
问题描述:
我有疑问在哪里设置我的代码中的套接字超时。我试图实现的是,当套接字创建时,超时应该是10秒。所以我在握手前设置它。现在我在日志中看到的错误有两种。 1)连接超时错误和2)读取超时错误。所以我想知道是否有人能更详细地解释我在哪里设置超时。我有以下代码:SSL连接超时和读取超时
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
请让我知道如何让超时到最低工作。在日志中,错误发生在18secs(不应该如此),而不是10secs。
谢谢
答
问题很可能是当创建套接字时连接超时已经发生。尝试使用无参数工厂方法首先实例化未连接的套接字,然后使用Socket#connect和timeout
选项以及Socket#setSoTimeout
。后者只踢了这些操作
的ServerSocket.accept()
SocketInputStream.read()
DatagramSocket.receive()
,但不处理连接超时期间尝试。
另请参阅technical article for networking timeouts了解更多详情。
感谢您的意见。我将在代码中实现这一点。另一件我关心的问题是,如果handshake()正常工作,socket.setSoTimeout(10000)是否适用于读写操作? – uppaljaskaran
@Jassi是的,它的确如此。读取超时时间为10秒;你需要确保它只捕获故障情况。我通常会将其设置为一两分钟。 – EJP