java-http/Main.java

42 lines
1.0 KiB
Java

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import workers.HandleClient;
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(3);
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 task = new HandleClient(client);
executor.submit(task);
} 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) {
}
}
}
}