Advertisement
rutera

Webserver

Oct 15th, 2013
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 4.89 KB | None | 0 0
  1. import java.io.* ;
  2. import java.net.* ;
  3. import java.util.* ;
  4.  
  5. public final class webserver2
  6. {
  7. public static void main(String argv[]) throws Exception
  8. {
  9. // Set the port number.
  10. int port = 9999;
  11.  
  12. // Establish the listen socket.
  13. ServerSocket welcomeSocket = new ServerSocket(port);
  14.  
  15. // Process HTTP service requests in an infinite loop.
  16. while (true) {
  17. // Listen for a TCP connection request.
  18. Socket connectionSocket = welcomeSocket.accept();
  19.  
  20. // Construct an object to process the HTTP request message.
  21. HttpRequest request = new HttpRequest( connectionSocket );
  22.  
  23. // Create a new thread to process the request.
  24. Thread thread = new Thread(request);
  25.  
  26. // Start the thread.
  27. thread.start();
  28. }}}
  29.  
  30.  
  31. final class HttpRequest implements Runnable
  32. {
  33. final static String CRLF = "\r\n";//returning carriage return (CR) and a line feed (LF)
  34. Socket socket;
  35.  
  36. // Constructor
  37.  public HttpRequest(Socket socket) throws Exception
  38.  {
  39.   this.socket = socket;
  40.  }
  41.  
  42. // Implement the run() method of the Runnable interface.
  43.  //Within run(), we explicitly catch and handle exceptions with a try/catch block.
  44. public void run()
  45. {
  46. try {processRequest();}catch (Exception e) {System.out.println(e);}
  47. }
  48.  
  49. private void processRequest() throws Exception
  50. {
  51. // Get a reference to the socket's input and output streams.
  52. InputStream instream = socket.getInputStream();
  53. DataOutputStream os = new DataOutputStream(socket.getOutputStream());
  54.  
  55. // Set up input stream filters.
  56. // Page 169 10th line down or so...
  57. BufferedReader br = new BufferedReader(new InputStreamReader(instream));//reads the input data
  58.  
  59. // Get the request line of the HTTP request message.
  60. String requestLine = br.readLine();// get /path/file.html version of http
  61.  
  62. // Display the request line.
  63. System.out.println();
  64. System.out.println(requestLine);
  65. // HERE WE NEED TO DEAL WITH THE REQUEST
  66. // Extract the filename from the request line.
  67. StringTokenizer tokens = new StringTokenizer(requestLine);// this is a input method with deliminators
  68. tokens.nextToken(); // skip over the method, which should be "GET"
  69. String fileName = tokens.nextToken();
  70.  
  71. // Prepend a "." so that file request is within the current directory.
  72. fileName = "." + fileName;
  73.  
  74. //Open the requested file.
  75.  
  76. FileInputStream fis = null;
  77. boolean fileExists = true;
  78. try {
  79.  fis = new FileInputStream(fileName);
  80. } catch (FileNotFoundException e) {
  81.  fileExists = false;
  82. }
  83.  
  84. //Construct the response message.
  85. String statusLine = null;
  86. String contentTypeLine = null;
  87. String entityBody = null;
  88.  
  89. if (fileExists) {
  90.  statusLine = "HTTP/1.0 200 OK" + CRLF; //common success message
  91.  contentTypeLine = "Content-type: " + contentType( fileName ) + CRLF;}//content info
  92.  
  93. else {
  94.  statusLine = "HTTP/1.0 404 Not Found" + CRLF;//common error message
  95.  contentTypeLine = "Content-type: " + "text/html" + CRLF;//content info
  96.  entityBody = "<HTML>" +
  97.   "<HEAD><TITLE>Not Found</TITLE></HEAD>" +
  98.   "<BODY>Not Found</BODY></HTML>";
  99. }
  100.  
  101.  
  102. //Send the status line.
  103. os.writeBytes(statusLine);
  104.  
  105. //Send the content type line.
  106. os.writeBytes(contentTypeLine);
  107.  
  108. //Send a blank line to indicate the end of the header lines.
  109. os.writeBytes(CRLF);
  110.  
  111.  
  112.  
  113. //Send the entity body.
  114. if (fileExists) {
  115.  sendBytes(fis, os);
  116.  os.writeBytes(statusLine);//Send the status line.
  117. os.writeBytes(contentTypeLine);//Send the content type line.
  118.  fis.close();
  119. } else {
  120.  os.writeBytes(statusLine);//Send the status line.
  121.  os.writeBytes(entityBody);//Send the an html error message info body.
  122.  os.writeBytes(contentTypeLine);//Send the content type line.
  123. }
  124.  
  125.  
  126. System.out.println("*****");
  127. System.out.println(fileName);//print out file request to console
  128. System.out.println("*****");
  129. // Get and display the header lines.
  130. String headerLine = null;
  131. while ((headerLine = br.readLine()).length() != 0) {
  132. System.out.println(headerLine);
  133. }
  134.  
  135. //code from part 1
  136. // Right here feed the client something
  137. //os.writeBytes("<html><body><h1>My First Heading</h1>");
  138. //os.writeBytes(  "<p>My first paragraph.</p></body></html> ");
  139. //os.flush();
  140.  
  141.  
  142. // Close streams and socket.
  143. os.close();
  144. br.close();
  145. socket.close();
  146.  
  147.  
  148.  
  149. }
  150. //return the file types
  151. private static String contentType(String fileName)
  152. {
  153.  if(fileName.endsWith(".htm") || fileName.endsWith(".html")) {return "text/html";}
  154.  if(fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {return "image/jpeg";}
  155.  if(fileName.endsWith(".gif")) {return "image/gif";}
  156.  return "application/octet-stream";
  157. }
  158.  
  159.  
  160. //set up input output streams
  161. private static void sendBytes(FileInputStream fis, OutputStream os) throws Exception
  162. {
  163.    // Construct a 1K buffer to hold bytes on their way to the socket.
  164.    byte[] buffer = new byte[1024];
  165.    int bytes = 0;
  166.  
  167.    // Copy requested file into the socket's output stream.
  168.    while((bytes = fis.read(buffer)) != -1 )// read() returns minus one, indicating that the end of the file
  169.    {
  170.       os.write(buffer, 0, bytes);
  171.    }}
  172. }
  173. //by rutera.org
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement