title: Simple Java Server with PrintWriter - problem sending a response to browser
body: <p>I've just started looking at HTTP etc. and have written a simple Java Client that uses URLConnection to send a URL to a server and pulls down the index.html page (as plain text).</p>
  
  <p>Now I'm working on a simple server but I'm stuck at the first hurdle, (well maybe 2nd or 3rd), I can't get it to respond to the client properly.</p>
  
  <p>Here is the reading in loop and it reads in the HTTP request fine, even from FF and IE etc:</p>
  
  <pre><code>while((message = in.readLine()) != null)
      {
          System.out.println(message);
          out.write("something");
      }
  </code></pre>
  
  <p>The problem is that I don't know how to get it to respond anything useful. If I let it do what it is doing in the above code it sends "something" 6 times to my client (as there are 6 lines to the HTTP request) but nothing to FF/IE etc.</p>
  
  <p>Also, it doesn't seem to break the loop ever as I added a <code>System.out.println("test");</code> line to print after the loop but the server never seems to reach that point, should it? Should readLine() return null at the end of the first HTTP request?</p>
  
  <p>I've been reading stuff on the sun and oracle websites but am still pretty stuck as to how this should work.</p>
  
  <p>Thanks for your time,</p>
  
  <p>Infinitifizz</p>
  
  <p>EDIT: Oops, forgot to copy the code in.</p>
  
  <p>Server.java:</p>
  
  <pre><code>package exercise2;
  
  import java.net.*;
  
  public class Server 
  {
      public static void main(String[] args) throws Exception
      {
          boolean listening = true;
          ServerSocket server = new ServerSocket(8081);
  
      while(listening)
      {
          Socket client = server.accept();
  
          new ServerThread(client).start();
      }
          server.close();
      }
  }
  </code></pre>
  
  <p>ServerThread.java:</p>
  
  <pre><code>package exercise2;
  
  import java.io.*;
  import java.net.*;
  
      public class ServerThread extends Thread 
  {
      private Socket socket = null;
      public ServerThread(Socket s)
      {
          this.socket = s;
      }
  
      public void run()
      {
          try
          {
  
          PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
          BufferedReader in = new BufferedReader(new InputStreamReader(
                                      socket.getInputStream()));
  
          String message, reply = "";
  
          while((message = in.readLine()) != null)
          {
              System.out.println(message);
              out.write("something");
          }
              System.out.println("test");
          in.close();
          out.close();
          socket.close();
          }
          catch(IOException e)
          {
              System.err.println("error");
          }
      }
  }
  </code></pre>