5

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

brain storm
  • 30,124
  • 69
  • 225
  • 393

2 Answers2

6

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.

Community
  • 1
  • 1
kamoor
  • 2,909
  • 2
  • 19
  • 34
5

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.

Naman
  • 2,205
  • 2
  • 19
  • 32
  • how does each thread that generates response and sends it back to the client. Does each thread have TCP port and address info? – brain storm Jan 28 '15 at 06:33
  • NO Thread doesn't contain those info.Requests from clients are received on a connector, which in turn funnels them through into the engine, which is the key request processing component within Tomcat. Any request that is received by any one of a service's connectors is passed on to the service's single engine. This engine, known as Catalina, is responsible for the processing of the request, and the generation of the response. The engine returns the response to the connector, which then transmits it back to the client using the appropriate communication protocol. – Naman Jan 28 '15 at 09:29
  • 1
    May this link helps http://tomcat.apache.org/tomcat-7.0-doc/architecture/requestProcess/requestProcess.pdf – Naman Jan 28 '15 at 09:33