~/ learn/ comp-348/ cards/ `ServerSocket` and the accept loop
1 of 5

The accept loop: one try for the server, one for each client

The accept loop: one try for the server, one for each client

Answer

try (ServerSocket listener = new ServerSocket(1313)) { while (true) { try (Socket client = listener.accept()) { serve(client); } catch (IOException ex) { System.err.println("dropped: " + ex.getMessage()); } } }

The inner catch is the whole point: it is inside the loop, so a failure while serving one client falls through to the next `accept()` instead of unwinding past the loop and ending the server. The outer try-with-resources owns the port and releases it when the server genuinely stops.

Harold 4e ch9 §Using ServerSockets

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/87802cbf-ef29-4cc7-adf5-2b2143f80941/flashcard utf-8 LF