raffaele181188

Minimal HTTP server

Dec 11th, 2012
1,214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.81 KB | None | 0 0
  1. package stackoverflow;
  2.  
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.OutputStream;
  6. import java.io.PrintStream;
  7. import java.net.ServerSocket;
  8. import java.net.Socket;
  9. import java.net.URL;
  10. import java.util.LinkedList;
  11. import java.util.List;
  12. import java.util.Scanner;
  13. import java.util.regex.Matcher;
  14. import java.util.regex.Pattern;
  15.  
  16. public class TinyHTTPServer {
  17.  
  18.     public static void main(String[] args) throws IOException {
  19.        
  20.         ServerSocket server = new ServerSocket(8888);
  21.        
  22.         while (true) {
  23.             final Socket connection = server.accept();
  24.             new Thread(new Runnable(){
  25.                 public void run() {
  26.                     RequestHandler handler = new RequestHandler();
  27.                     handler.handle(connection);
  28.                 }
  29.             }).start();
  30.         }
  31.     }
  32.    
  33.     public static class RequestHandler {
  34.        
  35.         public void handle(Socket socket) {
  36.             try {
  37.                 Scanner scanner = new Scanner(socket.getInputStream(), "US-ASCII");
  38.                 String path = getPath(scanner.nextLine());
  39.                
  40.                 Response response = find(path);
  41.                
  42.                 PrintStream out = new PrintStream(socket.getOutputStream());
  43.                
  44.                 for (String header : response.headers) {
  45.                     out.print(header);
  46.                     out.print("\r\n");
  47.                 }
  48.                
  49.                 out.print("\r\n");
  50.                 if (response.url != null)
  51.                     writeEntity(response.url.openStream(), socket.getOutputStream());
  52.                 out.print("\r\n");
  53.                
  54.                 out.flush();
  55.             } catch (Exception exception) {
  56.                 exception.printStackTrace();
  57.             } finally {
  58.                 try {
  59.                     socket.close();
  60.                 } catch (IOException e) {
  61.                     e.printStackTrace();
  62.                 }
  63.             }
  64.         }
  65.        
  66.         private String getPath(String requestLine) throws IOException {
  67.             Matcher matcher = Pattern.compile("GET (/\\S*) HTTP/1\\.1").matcher(requestLine);
  68.             matcher.find();
  69.             return matcher.group(1);
  70.         }
  71.        
  72.         private Response find(String path) {
  73.            
  74.             if (path.equals("/"))
  75.                 path = "/index.html";
  76.            
  77.             Response response = new Response();
  78.             URL url = RequestHandler.class.getResource(path);
  79.            
  80.             if (url == null) {
  81.                 response.headers.add("HTTP/1.1 404 NOT FOUND");
  82.             } else {
  83.                 response.url = url;
  84.                 response.headers.add("HTTP/1.1 200 OK");
  85.  
  86.                 String type = "application/octet-stream";
  87.                 String extension = url.toString();
  88.                
  89.                 if (extension.endsWith(".mp3"))
  90.                     type = "audio/mp3";
  91.                 else if (extension.endsWith(".html"))
  92.                     type = "text/html; charset=utf-8";
  93.                
  94.                 response.headers.add("Content-Type: " + type);
  95.             }
  96.            
  97.             return response;
  98.         }
  99.        
  100.         private void writeEntity(InputStream in, OutputStream out) throws IOException {
  101.             byte[] buffer = new byte[1024];
  102.             int read = -1;
  103.            
  104.             while ((read = in.read(buffer, 0, buffer.length)) > -1) {
  105.                 out.write(buffer, 0, read);
  106.             }
  107.         }
  108.        
  109.     }
  110.    
  111.     public static class Response {
  112.        
  113.         public List<String> headers = new LinkedList<String>();
  114.         public URL url;
  115.        
  116.     }
  117. }
Advertisement
Add Comment
Please, Sign In to add comment