开发者

When does Servlets read or write actual data

开发者 https://www.devze.com 2023-03-28 19:08 出处:网络
I 开发者_运维知识库was testing a Client Server Application to know when does a Servlet actually receives / writes a data to a Client.

I 开发者_运维知识库was testing a Client Server Application to know when does a Servlet actually receives / writes a data to a Client.

The test setup has a client Java program which reads a file and POSTs the file to a Servlet.

Only after the client finishes writing the whole file (4 MB) data to socket the server starts reading that data. Similarly, when a Servlet sends a response using PrintWriter, the response reaches the client only when the doPost(...) method in the Servlet returns. Thorought the testing Tomcat memory didn't increase atall...

When does the Servlet Connection / Session gets established? Why does the Servlet coudn't read the data immediately when the client writes first few bytes of data to socket?


That's just the way it works. The container will not invoke the servlet until the entire request is received from the client. Doing it any other way would imply any number of unforeseeable consequences. For starters, you would have to put manual completion checks in all your servlets, which would just add unnecessary boiler-plate code.

If you want to be able to react to HTTP requests from the moment they start being received, you will have to write your own socket program, binding and listening on a port and handling the input yourself.

Output is another matter. The output stream buffers all servlet output, but you can invoke flushBuffer() on the ServletResponse at any time to force it to send all currently buffered content. A warning about this though, once you start sending data to the client, the response is considered "committed". This is because of the HTTP protocol that requires certain pieces of information to come in a certain order. Headers, for instance, must be sent first, meaning that once you "commit" the response, headers and cookies can't be added by the server application anymore. The container will always call flushBuffer() (or flush() on the ServletOutputStream) after the servlet has finished executing.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号