Web server is a application which runs on server machine and listens request from various clients on specific port and gives some specific response for each request. Web servers and client machines uses sockets for transferring data between each other. In general if we construct simple web server using single execution instance then it will be able to serve only one client at time, so if multiple clients wants connect to the server then other clients may need to wait. To resolve this problem we can construct multithreaded server, which will create and execute a single thread  for each individual request (may be from same client machine or different client machines). Coding this in Java is very easy as compared to other languages.


Java Code of a multithreaded web server available here is able to accept requests from other computers (clients) by using their browser to point towards the server host and, in return displays a web pages or images. Following are steps to create multithreaded web server:

1. Create a Socket to listen webrequest on Port 80.
int port =80;
ServerSocket WebSocket = new ServerSocket(port);
2. Accept a TCP request
Socket connectionSocket = WebSocket.accept();
3. Construct an object to process HTTP request.
HttpRequest request = new HttpRequest(connectionSocket);
4. Create a thread to process requests.
Thread thread = new Thread(request);
thread.start(); //start thread

Note:   If you are testing this code with Eclipse or Netbeans IDEs then make one .html file, say index.html in root folder of your project and browse (similary for other .htlm files).



Join the Conversation


  1. hey, how can I know the number of times the file is being accessed before closing the socket ? Any thoughts…

Leave a comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: