| 11 | import java.util.concurrent.ExecutionException; |
| 12 | |
| 13 | public class JavaAsyncHTTPServer { |
| 14 | public static void main(String[] args) throws Exception { |
| 15 | new JavaAsyncHTTPServer().start(); |
| 16 | Thread.currentThread().join(); // Wait forever |
| 17 | } |
| 18 | |
| 19 | private void start() throws IOException { |
| 20 | // we shouldn't use try with resource here as it will kill the stream |
| 21 | var server = AsynchronousServerSocketChannel.open(); |
| 22 | server.bind(new InetSocketAddress("127.0.0.1", 8080), 100); // bind listener |
| 23 | server.setOption(StandardSocketOptions.SO_REUSEADDR, true); |
| 24 | System.out.println("Server is listening on port 8080"); |
| 25 | |
| 26 | final int[] count = {0}; // count used to introduce delays |
| 27 | |
| 28 | // listen to all incoming requests |
| 29 | server.accept(null, new CompletionHandler<>() { |
| 30 | @Override |
| 31 | public void completed(final AsynchronousSocketChannel result, final Object attachment) { |
| 32 | if (server.isOpen()) { |
| 33 | server.accept(null, this); |
| 34 | } |
| 35 | count[0]++; |
| 36 | handleAcceptConnection(result, count[0]); |
| 37 | } |
| 38 | |
| 39 | @Override |
| 40 | public void failed(final Throwable exc, final Object attachment) { |
| 41 | if (server.isOpen()) { |
| 42 | server.accept(null, this); |
| 43 | System.out.println("Connection handler error: " + exc); |
| 44 | } |
| 45 | } |
| 46 | }); |
| 47 | } |
| 48 | |
| 49 | private void handleAcceptConnection(final AsynchronousSocketChannel ch, final int count) { |
| 50 | var file = new File("hello.html"); |
| 51 | try (var fileIn = new FileInputStream(file)) { |
| 52 | // add 2 second delay to every 10th request |
| 53 | if (count % 10 == 0) { |
| 54 | System.out.println("Adding delay. Count: " + count); |
| 55 | Thread.sleep(2000); |
| 56 | } |
| 57 | if (ch != null && ch.isOpen()) { |
| 58 | // Read the first 1024 bytes of data from the stream |
| 59 | final ByteBuffer buffer = ByteBuffer.allocate(1024); |
| 60 | // read the request fully to avoid connection reset errors |
| 61 | ch.read(buffer).get(); |
| 62 | |
| 63 | // read the HTML file |
| 64 | var fileLength = (int) file.length(); |
| 65 | var fileData = new byte[fileLength]; |
| 66 | fileIn.read(fileData); |
| 67 | |
| 68 | // send HTTP Headers |
| 69 | var message = ("HTTP/1.1 200 OK\n" + |
| 70 | "Connection: keep-alive\n" + |
nothing calls this directly
no outgoing calls
no test coverage detected