Programming
Creating multithreaded web server in Java
      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 http://127.0.0.1/index.html (similary for other .htlm files).

 

 

Related Post

2 Comments

  1. Darshan

    where is the client code for this ? Please need help on that.

    • Shubham Takode

      you can use your browser as client.. to send http request

Leave a Reply