【问题标题】:Why does my TCP socket take a long time to read a response?为什么我的 TCP 套接字需要很长时间才能读取响应?
【发布时间】:2021-07-06 08:44:54
【问题描述】:

我正在为大学做一些工作,其中要求我创建一个 TCP 套接字,该套接字以 OPTIONS 作为标头发出 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分钟多,但响应日期与请求相同。

我可以做些什么来加快响应速度?

【问题讨论】:

  • 3 分钟听起来有点像保命
  • 不完全是 3 分钟,大约是 3 分钟

标签: java performance sockets tcp


【解决方案1】:
    wtr.println("OPTIONS / HTTP/1.1");
    wtr.println("Host: " + url);
    wtr.println("");

您正在执行一个 HTTP/1.1 请求,该请求隐式启用 HTTP 保持活动状态。这意味着服务器可能会在同一 TCP 连接上等待另一个请求。

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

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

【讨论】:

猜你喜欢
  • 2019-05-27
  • 1970-01-01
  • 2017-03-16
  • 1970-01-01
  • 1970-01-01
  • 2019-06-17
  • 2020-09-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多