Compare commits

...

2 Commits

Author SHA1 Message Date
andrzej 61777d5581 add 404 page 2024-11-11 12:30:50 +01:00
andrzej 4ac130b9d2 handle exceptions 2024-11-11 12:30:43 +01:00
3 changed files with 28 additions and 4 deletions

9
404.html Normal file
View File

@ -0,0 +1,9 @@
<html>
<head>
<title>404</title>
</head>
<body>
<h1>UH-OH</h1>
<p>The page you were looking for could not be found.</p>
</body>
</html>

View File

@ -12,15 +12,29 @@ import java.util.List;
public class Main { public class Main {
public static void main(String[] args) throws Exception { public static void main(String[] args) {
int attempts = 1;
try (ServerSocket serverSocket = new ServerSocket(8080)) { try (ServerSocket serverSocket = new ServerSocket(8080)) {
System.out.println("listening on socket 8080..."); System.out.println("listening on socket 8080...");
while (true) { while (true) {
// .accept() blocks until we have a client // .accept() blocks until we have a client
try (Socket client = serverSocket.accept()) { try (Socket client = serverSocket.accept()) {
handleClient(client); handleClient(client);
} catch (IOException e) {
System.out.printf("Error accepting client: %s\n", e);
} }
} }
} catch (IOException e) {
System.out.printf("Error opening port (attempt %s) %s:\n", attempts, e);
if (attempts > 3) {
System.out.println("This isn't working. Shutting down.");
System.exit(1);
}
try {
Thread.sleep(1000);
} catch (InterruptedException ignore) {
}
} }
} }
@ -33,7 +47,9 @@ public class Main {
String line; String line;
while (!(line = br.readLine()).isBlank()) { while (!(line = br.readLine()).isBlank()) {
requestBuilder.append(line + "\r\n"); requestBuilder.append(line + "\r\n");
} }
String request = requestBuilder.toString(); String request = requestBuilder.toString();
// System.out.println(request); // System.out.println(request);
// PARSE THE REQUEST // PARSE THE REQUEST
@ -63,8 +79,7 @@ public class Main {
sendResponse(client, "200 OK", contentType, Files.readAllBytes(filepath)); sendResponse(client, "200 OK", contentType, Files.readAllBytes(filepath));
} else { } else {
// 404 // 404
byte[] notFoundContent = "<h1>404 Something went wrong</h1>".getBytes(); sendResponse(client, "404 Not Found", "text/html", Files.readAllBytes(getFilePath("404.html")));
sendResponse(client, "404 Not Found", "text/html", notFoundContent);
} }
} }

View File

@ -1,4 +1,4 @@
<<head> <head>
<header> <header>
<title>JAVA SERVER TEST</title> <title>JAVA SERVER TEST</title>
</header> </header>