【问题标题】:SSL Connection timeout and read timeoutsSSL 连接超时和读取超时
【发布时间】:2011-12-05 18:12:47
【问题描述】:

我对在我的代码中设置套接字超时的位置有疑问。我想要实现的是,当创建套接字时,超时应该是 10 秒。所以我在握手之前设置它。现在我在日志中看到的错误有两种。 1) 连接超时错误和 2) 读取超时错误。所以我想知道是否有人可以向我解释更多关于在哪里设置超时的信息。我有以下代码:

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

请让我知道我怎样才能让至少工作超时。在日志中,错误发生在 18 秒(不应该是这种情况)而不是 10 秒。

谢谢

【问题讨论】:

    标签: java sockets ssl settimeout connection-timeout


    【解决方案1】:

    问题很可能是在创建套接字时连接时已经发生超时。尝试首先使用无参数工厂方法实例化一个未连接的套接字,然后使用Socket#connecttimeout 选项以及Socket#setSoTimeout。后者只对这些操作起作用

    ServerSocket.accept()

    SocketInputStream.read()

    DatagramSocket.receive()

    但在连接尝试期间不处理超时。

    有关更多详细信息,另请参阅technical article for networking timeouts

    【讨论】:

    • 感谢您的意见。我将在代码中实现这一点。我担心的另一件事是,如果握手()顺利进行,socket.setSoTimeout(10000)是否适用于读写操作???
    • @Jassi 是的。 10 秒对于读取超时来说是相当短的;您需要确保它只捕获失败案例。我通常会将其设置为一两分钟。
    猜你喜欢
    • 2017-09-28
    • 2021-12-27
    • 1970-01-01
    • 2019-02-01
    • 2013-12-07
    • 2021-12-08
    • 2017-10-29
    • 1970-01-01
    • 2022-08-24
    相关资源
    最近更新 更多