java - SSL 连接超时和读取超时

标签 java sockets ssl settimeout connection-timeout

我对在代码中的何处设置套接字超时有疑问。我想要实现的是,当创建套接字时,超时应该是 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 秒。

谢谢

最佳答案

问题很可能是在创建套接字时连接超时。首先尝试使用无参数工厂方法实例化一个未连接的套接字,然后使用 Socket#connect除了 Socket#setSoTimeout 之外,还有 timeout 选项。后者只为这些操作启动

ServerSocket.accept()

SocketInputStream.read()

DatagramSocket.receive()

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

另见 technical article for networking timeouts了解更多详情。

关于java - SSL 连接超时和读取超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7734188/

相关文章:

java - Java IDE (NetBeans) 的奇怪行为

Java 消息被发送到一个关闭的套接字

c++ - 尝试更改结构 C/C++ 中的字符串时出现 SIGSEGV

ssl - 使用 keytool 导入 Java keystore 后,站点证书序列号发生更改

security - *intranet* REST API 调用应该如何保护?

java - 我应该将serialVersionUID设置为什么?

java - 元素位置中的 Xpath 问题

azure - 使用 RDM 使用 SSL 通过 Ngnix 安全连接到 Redis 容器

java - 在隐藏字段值中插入换行符 - Java

java - 如何从 GPSD 检索数据并在 Android 客户端中使用它们