Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package es.udc.redes.webserver;
- import java.net.*;
- import java.io.*;
- import java.util.Date;
- public class ServerThread extends Thread {
- private Socket socket;
- public ServerThread(Socket s) {
- // Store the socket s
- this.socket = s;
- }
- private static String getContentType(File file) {
- String name = file.getName();
- String extension = name.substring(name.lastIndexOf(".") + 1);
- String contentType;
- switch (extension) {
- case "html":
- contentType = "text/html";
- break;
- case "txt":
- contentType = "text/plain";
- break;
- case "css":
- contentType = "text/css";
- break;
- case "js":
- contentType = "application/javascript";
- break;
- case "jpg":
- case "jpeg":
- contentType = "image/jpeg";
- break;
- case "gif":
- contentType = "image/gif";
- break;
- case "png":
- contentType = "image/png";
- break;
- case "ico":
- contentType = "image/x-icon";
- break;
- default:
- contentType = "application/octet-stream";
- }
- return contentType;
- }
- public void run() {
- try {
- // This code processes HTTP requests and generates
- // HTTP responses
- BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
- OutputStream out = socket.getOutputStream();
- String peticion = in.readLine();
- String[] parts = peticion.split(" ");
- String metodo = parts[0];
- String url = parts[1];
- if (metodo.equals("GET")) {
- File file = new File(System.getProperty("user.dir") + File.separator + "p1-files" + File.separator + url);
- if (file.exists()) {
- FileInputStream fis = new FileInputStream(file);
- byte[] data = new byte[(int) file.length()];
- fis.read(data);
- fis.close();
- String contentType = getContentType(file);
- Date fecha = new Date(file.lastModified());
- String response = "HTTP/1.0 200 OK\r\n" +
- "Content-Length: " + data.length + "\r\n" +
- "Content-Type: " + contentType + "\r\n" +
- "Last modified: " + fecha +
- "\r\n";
- out.write(response.getBytes());
- out.write(data);
- System.out.println(response);
- } else {
- String response = "HTTP/1.0 404 Not Found\r\n" +
- "\r\n";
- out.write(response.getBytes());
- }
- } else if(metodo.equals("HEAD")){
- System.out.println("Programar método HEAD");
- } else{
- String response = "HTTP/1.0 400 Bad Request\r\n" +
- "Allow: GET, HEAD\r\n" +
- "\r\n";
- out.write(response.getBytes());
- }
- in.close();
- out.close();
- socket.close();
- // Uncomment next catch clause after implementing the logic
- //
- } catch (SocketTimeoutException e) {
- System.err.println("Nothing received in 300 secs");
- } catch (Exception e) {
- System.err.println("Error: " + e.getMessage());
- } finally {
- // Close the client socket
- }
- }
- }
Add Comment
Please, Sign In to add comment