【问题标题】:SSLSocket client's input stream could not recieve anything from serverSSLSocket 客户端的输入流无法从服务器接收任何内容
【发布时间】:2017-04-06 15:40:04
【问题描述】:

我正在尝试制作一个将 GET 请求发送到任何 https 服务器的 TLS 客户端。 但是,当它第二次尝试发送 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

【问题讨论】:

    标签: java sockets inputstream


    【解决方案1】:

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

    【讨论】:

    • 谢谢你,亚历克斯。应该查看 HTTP 协议规范
    【解决方案2】:

    如果我不得不猜测,我会说它是因为你没有关闭你的套接字并打开一个新的,所以就 Web 服务器而言,它是相同的请求。

    EG:

    你:获取 /INDEX.HTML
    服务器:${FILE_CONTENTS}

    此时,您的请求已完成,如果我没记错的话,服务器应该关闭它们的套接字端,但我可能错了

    你真正应该做的是每次都为那个服务器创建一个新的套接字,写你的请求,得到响应,关闭套接字,冲洗并重复

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-21
      • 1970-01-01
      • 1970-01-01
      • 2012-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多