为什么我的 TCP 套接字需要很长时间才能读取响应?

Why does my TCP socket take a long time to read a response?

我正在为大学做一些工作,其中要求我创建一个 TCP 套接字,该套接字使用 OPTIONS 作为 header 和 return 发出 HTTP 请求变量中的页面。

我做的代码如下:

public String SendReq(String url, int port) throws Exception {

        String resposta = null;
        // Instantiate a new socket
        Socket s = new Socket(url, port);

        // Instantiates a new PrintWriter passing in the sockets output stream
        PrintWriter wtr = new PrintWriter(s.getOutputStream());

        // Prints the request string to the output stream
        wtr.println("OPTIONS / HTTP/1.1");
        wtr.println("Host: " + url);
        wtr.println("");
        wtr.flush();
        // Creates a BufferedReader that contains the server response
        BufferedReader bufRead = new BufferedReader(new InputStreamReader(s.getInputStream()));
        String outStr;
 
        
        while ((outStr = bufRead.readLine()) != null) {

            resposta = resposta + outStr;
            
            if (!outStr.trim().isEmpty()) {
                resposta += "\r\n";
            }
        }

        LSimLogger.log(Level.INFO, "response http : " + resposta);

        s.close();
        bufRead.close();
        wtr.close();
        return resposta ;
    }

而且确实有效。

如您所见,我 运行 这段代码 example.org 作为 url 和 80 作为端口。在日志中,我看到:

10-04-2021 21:35:49:514 tcp_client [INFO] : inici client http
10-04-2021 21:35:49:517 tcp_client [INFO] : inici HTTPclient.get 
10-04-2021 21:35:49:517 tcp_client [INFO] : HTTP server_address: example.org
10-04-2021 21:35:49:517 tcp_client [INFO] : HTTP server_port: 80
10-04-2021 21:35:49:517 tcp_client [INFO] : example.org
10-04-2021 21:38:00:636 tcp_client [INFO] : response http : nullHTTP/1.1 200 OK
Allow: OPTIONS, GET, HEAD, POST
Cache-Control: max-age=604800
Content-Type: text/html; charset=UTF-8
Date: Sat, 10 Apr 2021 19:35:49 GMT
Expires: Sat, 17 Apr 2021 19:35:49 GMT
Server: EOS (vny/0452)
Content-Length: 0

如您所见,得到响应需要3分钟多,但是响应的日期与请求的日期相同。

我怎样才能使响应更快?

    wtr.println("OPTIONS / HTTP/1.1");
    wtr.println("Host: " + url);
    wtr.println("");

您正在执行 HTTP/1.1 请求,该请求隐式启用 HTTP keep-alive。这意味着服务器可能会等待同一 TCP 连接上的另一个请求。

只有您的代码希望服务器在响应后立即关闭连接。但是服务器并没有这样做,而是等待更多的请求一段时间,直到几分钟后才停止等待。

要解决此问题,您需要正确读取 HTTP 响应并按照 HTTP 标准检测响应何时完成。或者通过在请求中添加 Connection: close header 来确保 HTTP keep-alive 已关闭。