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

时间:2017-04-06 15:40:04

标签: java sockets inputstream

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

2 个答案:

答案 0 :(得分:2)

That's because your HTTP connection is not persistent (note the Connection: close header in the response). You need to either add Connection: keep-alive header to the request or switch to HTTP 1.1 (connections are persistent by default). Otherwise you'll have to create new TCP connection for each request.

答案 1 :(得分:0)

If i had to make a guess, I'd say its because you're not closing your socket and opening a new one, so as far as the web server is concerned, it's the same request.

EG:

YOU: GET /INDEX.HTML
SERVER: ${FILE_CONTENTS}

at that point, your request is done, the server should close their end of the socket, if i recall correctly, but I may be wrong

What you really should do is make a new socket to that server every time, write your request, get the response, close the socket, rinse and repeat