Exemplo n.º 1
0
  /**
   * Helper method for handling a client connection. If the file is a directory, a directory listing
   * is generated as a text file. Closes the socket (and therefore the associated streams) when the
   * method returns.
   *
   * @param s Socket representing the client connection
   * @throws IOException
   */
  private void handleConnection(Socket s) {
    InputStream in = null;
    PrintStream out = null;
    try {
      in = s.getInputStream();
      out = new PrintStream(s.getOutputStream());

      List<String> headers = new ArrayList<String>();

      // first line is request
      String request = readLine(in);
      System.out.println("Initial Request: " + request);
      headers.add(request);

      // read and display remaining headers
      String line;
      while (true) {
        line = readLine(in);
        if (line.length() == 0) {
          break; // blank line is end of headers
        }
        headers.add(line);
        System.out.println("Header line read from request: " + line);
      }
      System.out.println("~end of headers~");

      parseRequest(headers, in, out);

    } catch (IOException e) {
      System.out.println(e);
    } finally {
      if (s != null) {
        try {
          s.close();
        } catch (IOException ignore) {
        }
      }
    }
  }