From 4ac130b9d264fa691b2aad95cb1f2bebb8dc2d2c Mon Sep 17 00:00:00 2001 From: andrzej Date: Mon, 11 Nov 2024 12:21:25 +0100 Subject: [PATCH] handle exceptions --- Main.java | 18 +++++++++++++++++- index.html | 2 +- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/Main.java b/Main.java index 8726425..b373e30 100644 --- a/Main.java +++ b/Main.java @@ -12,15 +12,29 @@ import java.util.List; 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)) { System.out.println("listening on socket 8080..."); while (true) { // .accept() blocks until we have a client try (Socket client = serverSocket.accept()) { 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; while (!(line = br.readLine()).isBlank()) { requestBuilder.append(line + "\r\n"); + } + String request = requestBuilder.toString(); // System.out.println(request); // PARSE THE REQUEST diff --git a/index.html b/index.html index 7ae8f03..e2bb022 100644 --- a/index.html +++ b/index.html @@ -1,4 +1,4 @@ -< +
JAVA SERVER TEST