The shape of every client you will write: try-with-resources on the socket itself.
The shape of every client you will write: try-with-resources on the socket itself.
Answer
try (Socket socket = new Socket("www.example.com", 80)) { socket.setSoTimeout(15_000); Writer out = new OutputStreamWriter( socket.getOutputStream(), StandardCharsets.US_ASCII); out.write("GET / HTTP/1.1\r\nHost: www.example.com\r\nConnection: close\r\n\r\n"); out.flush(); socket.getInputStream().transferTo(System.out); }
The resource in the header is the socket, so the exit path closes the connection and both streams however the block ends. The charset is stated, never inherited from the platform. `flush()` is what actually puts the request on the wire, and `transferTo` drains the reply until the server closes.
Harold 4e ch8 §Using Sockets