Thursday 28 July 2011

Http Server Implementing GET

Hi all,

Had to create a very very simple http server, that only implements the GET function, in Java for one of our assignments.
When run you can get file from your computer using http://127.0.0.1:8001/filename.jpg.

Could use this kind of thing for some multiplayer game in the future.

Am currently working on an augmented reality program. Should be AWESOME!


Am also testing out a new code formatter. Hopefully things become readable. Unfortunately tabs do not appear as tabs... Big thanks to David Craft.

Here's the code for the server.

import java.net.ServerSocket;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.util.StringTokenizer;

/**
 * @author Milk
 *
 */
public class HttpServer {

 /**
  * 
  * @param args
  */
 public static void main(String[] args) {
  try {
   ServerSocket socket = new ServerSocket(8001);
   InetAddress serverHost = InetAddress.getLocalHost();
   System.out.println("Server destination: " + serverHost.getHostAddress() + 
     ", "+ socket.getLocalPort());
   // Repeatedly handle requests for processing.
   while(true){
    Socket clientConnection = socket.accept();
    System.err.println("Connection established.");
    BufferedReader in = new BufferedReader(new InputStreamReader(
      clientConnection.getInputStream()));
    DataOutputStream out = new DataOutputStream(clientConnection.getOutputStream());
    // Read string.
    String inString = in.readLine();
    System.out.println(inString);
    StringTokenizer st = new StringTokenizer(inString);
    st.nextToken();
    String request = "." + st.nextToken();
    // Read the requested file.
    FileInputStream f;
    try{
     f = new FileInputStream(new File(request));
     sendFile(f, out);
    } catch (FileNotFoundException e){
     try{
     // Display 404 screen.
     f = new FileInputStream(new File("./404.jpg"));
     sendFile(f, out);
     } catch (FileNotFoundException e2){
      out.writeBytes("HTTP/1.0 404 Not Found\r\n");
     }
    }
    // Close this connection.
    clientConnection.close();
    System.err.println("Connection closed.");
   }
  }
  catch(IOException e) {
   e.printStackTrace();
  }
 }
 
 /**
  * Sends the file.
  * @param f The file to be sent.
  * @param out The DataOutputStream.
  * @throws IOException
  */
 private static void sendFile(FileInputStream f, DataOutputStream out) throws IOException{
  // Send the file byte by byte.
  while(true){
   int b = f.read();
   if (b == -1){
    break;
   }
   out.write(b);
  }
 }
}

Cheers,
Milk

1 comment: