title: Java: Implementing a Multithreaded web server
body: <p>Trying to work on <a href="http://www.cs.bu.edu/fac/matta/Teaching/CS552/F99/proj4/" rel="nofollow">this assignment</a> for practice. Got stuck few with two issues.</p>
  
  <ol>
  <li>Where should I stop the Thread after printing the request on console? Later I would need to do that after sending the response.</li>
  <li>From where should I send the response back? I can easily do it from <code>processRequest()</code>. Was thinking if there is anyway to send a HttpResponse back.
  Would it be ok to send the response back from HttpRequest class itself? </li>
  </ol>
  
  <p><strong>Code</strong></p>
  
  <p>Main class</p>
  
  <pre><code>public final class WebServer {
  
      public static void main(String[] args) throws Exception {
          int port = 1983;
          final ServerSocket server = new ServerSocket(port);
          System.out.println("Comes here");
          Socket client = null;
          while (true) {
              client = server.accept();
              System.out.println("Got the connection" + client.toString());
              final HttpRequest request = new HttpRequest(client);
              Thread thread = new Thread(request);
              thread.start();
  
          }
      }
  
  }
  </code></pre>
  
  <p><strong>HttpRequest.java</strong></p>
  
  <pre><code>final class HttpRequest implements Runnable {
  
      Socket socket;
  
      public HttpRequest(Socket socket) {
          this.socket = socket;
      }
  
      @Override
      public void run() {
          try {
              processRequest();
          } catch (IOException e) {
              e.printStackTrace();
          }
      }
  
      private void processRequest() throws IOException {
          String headerline = null;
          DataOutputStream out = null;
          BufferedReader in = null;
          out = new DataOutputStream(socket.getOutputStream());
          in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  
          while ((headerline = in.readLine()).length() != 0) {
              System.out.println(headerline);
          }
          out.close();
          in.close();
          socket.close();
      }
  
  }
  </code></pre>