gpt4 book ai didi

java - SSLSocket 客户端的输入流无法从服务器接收任何内容

转载 作者:行者123 更新时间:2023-12-02 02:54:56 24 4
gpt4 key购买 nike

我正在尝试创建一个 TLS 客户端,它将向任何 https 服务器发送 GET 请求。但是,当服务器尝试第二次或更多次发送 GET 请求时,没有来自服务器的输入。我不明白为什么它会跳过其他响应。

客户端代码:

public class Main {

private static final String HOST = "testserver.com";
private static final int PORT = 443;

public static void main(String[] args) throws IOException {
BufferedReader socketReader;
PrintWriter socketWriter;

SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(HOST, PORT);
sslSocket.setKeepAlive(true);
sslSocket.setUseClientMode(true);
sslSocket.setEnabledProtocols(new String[] { "TLSv1.2" });
sslSocket.setEnabledCipherSuites(new String[] { "TLS_RSA_WITH_AES_128_CBC_SHA" });
sslSocket.startHandshake();

socketWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sslSocket.getOutputStream())));
socketReader = new BufferedReader(new InputStreamReader(sslSocket.getInputStream()));

while (true) {
socketWriter.print("GET / HTTP/1.0\r\n");
socketWriter.print("Accept: text/plain, text/html, text/*\r\n");
socketWriter.print("\r\n");
socketWriter.flush();

String inputLine;
while ((inputLine = socketReader.readLine()) != null) {
System.out.println(inputLine);
}

System.out.println("Finished sending GET Request");
}

}

输出示例:

HTTP/1.1 200 OK
Server: nginx/1.10.1
Date: Thu, 06 Apr 2017 15:37:21 GMT
Content-Type: text/html
Content-Length: 110
Last-Modified: Fri, 31 Mar 2017 19:19:44 GMT
Connection: close
Vary: Accept-Encoding
ETag: "58deabd0-6e"
Accept-Ranges: bytes
<html>
<head>
<title>TEST SERVER</title>
</head>
<body>
TEST
</body>
</html>
Finished sending GET Request

Finished sending GET Request

Finished sending GET Request

Finished sending GET Request

最佳答案

那是因为您的 HTTP 连接不是 persistent (请注意响应中的 Connection: close header )。您需要将 Connection: keep-alive header 添加到请求中或切换到 HTTP 1.1(默认情况下连接是持久的)。否则,您将必须为每个请求创建新的 TCP 连接。

关于java - SSLSocket 客户端的输入流无法从服务器接收任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43259767/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com