java-http/Main.java

97 lines
3.0 KiB
Java
Raw Normal View History

2024-11-10 15:45:43 +00:00
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
2024-11-10 17:52:15 +00:00
import java.io.OutputStream;
2024-11-10 15:31:35 +00:00
import java.net.ServerSocket;
import java.net.Socket;
2024-11-10 18:33:10 +00:00
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
2024-11-10 17:52:15 +00:00
import java.util.ArrayList;
import java.util.List;
2024-11-10 15:31:35 +00:00
public class Main {
public static void main(String[] args) throws Exception {
try (ServerSocket serverSocket = new ServerSocket(8080)) {
System.out.println("listening on socket 8080...");
while (true) {
2024-11-10 17:52:15 +00:00
// .accept() blocks until we have a client
2024-11-10 15:31:35 +00:00
try (Socket client = serverSocket.accept()) {
handleClient(client);
}
}
}
}
2024-11-10 15:45:43 +00:00
public static void handleClient(Socket client) throws IOException {
System.out.println("Debug: got new client" + client.toString());
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
StringBuilder requestBuilder = new StringBuilder();
String line;
while (!(line = br.readLine()).isBlank()) {
requestBuilder.append(line + "\r\n");
}
String request = requestBuilder.toString();
2024-11-10 17:52:15 +00:00
// System.out.println(request);
2024-11-10 18:33:10 +00:00
// PARSE THE REQUEST
2024-11-10 17:52:15 +00:00
String[] requestLines = request.split("\r\n");
String[] requestLine = requestLines[0].split(" ");
String method = requestLine[0];
String path = requestLine[1];
String version = requestLine[2];
String host = requestLines[1].split(" ")[1];
2024-11-10 15:31:35 +00:00
2024-11-10 17:52:15 +00:00
List<String> headers = new ArrayList<>();
// we start the loop from 2 because 0 is GET / HTTP/1.1 and 1 is the host
for (int h = 2; h < requestLines.length; h++) {
String header = requestLines[h];
headers.add(header);
}
String accessLog = String.format("Client %s, method %s, path %s, version %s, host %s, headers %s",
client.toString(),
method, path, version, host, headers.toString());
System.out.println(accessLog);
2024-11-10 18:33:10 +00:00
Path filepath = getFilePath(path);
if (Files.exists(filepath)) {
// file exist
String contentType = guessContentType(filepath);
sendResponse(client, "200 OK", contentType, Files.readAllBytes(filepath));
} else {
// 404
byte[] notFoundContent = "<h1>404 Something went wrong</h1>".getBytes();
sendResponse(client, "404 Not Found", "text/html", notFoundContent);
}
}
private static void sendResponse(Socket client, String status, String contentType, byte[] content)
throws IOException {
2024-11-10 17:52:15 +00:00
OutputStream clientOutput = client.getOutputStream();
clientOutput.write("HTTP/1.1 200 OK\r\n".getBytes());
clientOutput.write("ContentType: text/html\r\n".getBytes());
clientOutput.write("\r\n".getBytes());
2024-11-10 18:33:10 +00:00
clientOutput.write(content);
// These (windows) newlines indicate that the response is over
2024-11-10 17:52:15 +00:00
clientOutput.write("\r\n\r\n".getBytes());
clientOutput.flush();
client.close();
2024-11-10 15:31:35 +00:00
}
2024-11-10 18:33:10 +00:00
private static String guessContentType(Path filepath) throws IOException {
return Files.probeContentType(filepath);
}
private static Path getFilePath(String path) {
if ("/".equals(path)) {
path = "/index.html";
}
return Paths.get("/home/andrzej/dev/java-http", path);
}
2024-11-10 15:31:35 +00:00
}