0
@SpringBootApplication
@RestController
public class HttpChunkedApplication {

    public static void main(String[] args) {
        SpringApplication.run(HttpChunkedApplication.class, args);
    }

    @PostMapping("/home/getMsg")
    public ChunkedRsp login( HttpServletResponse response ){
        return new ChunkedRsp("aaa","bbb","ccc");
    }
}
@Data
public class ChunkedRsp {
   private String A;
   private String B;
   private String C;

    public ChunkedRsp(String a, String b, String c) {
        A = a;
        B = b;
        C = c;
    }
}

run the application, then

  1. sudo tcpdump -i any -nnAls0 port 8080
  2. curl -X POST http://0.0.0.0:8080/home/getMsg

tcpdump shows two data packet: tcp dump packet when I curl

SevenHu
  • 1
  • 3

1 Answers1

0

What you describe is exactly how chunked encoding should work (see e.g. Wikipedia):

  • every chunk is prefixed with its length (in hexadecimal) and \r\n,
  • the sequence 0\r\n\r\n indicates the end of the message.

The number of TCP segments sent depends on your TCP/IP stack (Operating System). If the connection is slow and the TCP_NO_DELAY option is false, the segments will be merged: see this question.

Tomcat by default sets the TCP_NO_DELAY option to true on the sockets (cf. documentation). To disable it, modify your connector configuration:

<Connector port="8080"
           socket.tcpNoDelay="false"
           ... />

and test your server on a real connection (not the loopback device 127.0.0.1, which is extremely fast).

Piotr P. Karwasz
  • 12,857
  • 3
  • 20
  • 43
  • springboot will use chunked response when return an object. if return a string, response will not chunked. – SevenHu Oct 18 '21 at 04:48
  • Yes, it does. So your problem is not the two TCP segments, but the fact that Spring Boot uses chunked encoding? You should clarify it by modifying your question. – Piotr P. Karwasz Oct 18 '21 at 04:52
  • why chunked response will send two TCP segments ? I find outputStream.flush() will send two TCP segments, but outputStream.write() will merge two TCP segments in one. – SevenHu Oct 18 '21 at 12:25