java-http/Main.java

42 lines
1.0 KiB
Java
Raw Permalink Normal View History

2024-11-10 15:45:43 +00:00
import java.io.IOException;
2024-11-10 15:31:35 +00:00
import java.net.ServerSocket;
import java.net.Socket;
2024-11-11 13:42:25 +00:00
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import workers.HandleClient;
2024-11-10 15:31:35 +00:00
public class Main {
2024-11-11 11:21:25 +00:00
public static void main(String[] args) {
2024-11-11 13:42:25 +00:00
ExecutorService executor = Executors.newFixedThreadPool(3);
2024-11-11 11:21:25 +00:00
int attempts = 1;
2024-11-10 15:31:35 +00:00
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()) {
2024-11-11 13:42:25 +00:00
HandleClient task = new HandleClient(client);
executor.submit(task);
2024-11-11 11:21:25 +00:00
} catch (IOException e) {
System.out.printf("Error accepting client: %s\n", e);
2024-11-10 15:31:35 +00:00
}
}
2024-11-11 11:21:25 +00:00
} 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) {
}
2024-11-10 15:31:35 +00:00
}
}
}