Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does Tomcat or any webserver handles requests and dispatches responses?

This might be a simple questions. But I am looking for low level details which I dont find a clear answer for.

I have a simple jsp form with a name field on it. I post my name to the form and the servlet returns with the response "Hello Matt" (here the name is what I posted on the form).

Now I have many clients (different browsers and tabs) posting to the servlet and getting responses back. How does Tomcat (or any webserver) knows where to send the response back. That is how does each servlet thread knows to which client the response should be dispatched to? where does these information are maintained in Tomcat?

Thanks

like image 697
brain storm Avatar asked Jan 28 '15 01:01

brain storm


2 Answers

Tomcat relies on java.net.Socket and other related classes. It runs on TCP port(Default: 8080) and identifies each request by IP address of host and TCP port used by host to connect to Tomcat. A HTTP request is sent by the browser over this connection. Tomcat contains pool of threads to handle multiple HTTP requests. For each request tomcat assigns a thread from its pool to handle request.When the response has been generated and sent back, this thread gets free and ready to serve another request.

like image 92
Naman Avatar answered Nov 15 '22 04:11

Naman


Java has built in server socket java.net.ServerSocket implementation which is used to accept TCP connection from any client. Once server accept a connection from a client it can send any message back to client as well. Tomcat implements HTTP protocol and communicate with client in HTTP protocol format.

This article talks little bit about tomcat implementation details. You also go through tomcat source code to understand the work flow.

Few important classes/packages:

org.apache.tomcat.util.net.ServerSocketFactory

org.apache.tomcat.util.net

You can actually write a simple HTTP server by using ServerSocket and write message to the socket in format followed by HTTP RFC. See this question to understand the basics.

like image 42
kamoor Avatar answered Nov 15 '22 03:11

kamoor