java 36 lines · 8 steps

Reading a socket with connect and read timeouts

A blocking socket client that bounds connection time, read time, and response size to stay resilient against slow or malicious peers.

Explained by highlit
1public class TimedSocketReader {
2 
3 private static final int READ_TIMEOUT_MS = 5_000;
4 private static final int CONNECT_TIMEOUT_MS = 3_000;
5 
6 public byte[] fetch(String host, int port, byte[] request, int maxResponseBytes) throws IOException {
7 try (Socket socket = new Socket()) {
8 socket.connect(new InetSocketAddress(host, port), CONNECT_TIMEOUT_MS);
9 socket.setSoTimeout(READ_TIMEOUT_MS);
10 
11 OutputStream out = socket.getOutputStream();
12 out.write(request);
13 out.flush();
14 
15 InputStream in = new BufferedInputStream(socket.getInputStream());
16 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
17 byte[] chunk = new byte[8192];
18 
19 try {
20 int read;
21 while ((read = in.read(chunk)) != -1) {
22 buffer.write(chunk, 0, read);
23 if (buffer.size() > maxResponseBytes) {
24 throw new IOException("Response exceeded " + maxResponseBytes + " bytes");
25 }
26 }
27 } catch (SocketTimeoutException e) {
28 socket.close();
29 throw new IOException("Read timed out after " + READ_TIMEOUT_MS + "ms; "
30 + buffer.size() + " bytes received", e);
31 }
32 
33 return buffer.toByteArray();
34 }
35 }
36}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Separate connect and read timeouts guard against both unreachable hosts and stalled mid-transfer peers.
  2. 2Try-with-resources guarantees the socket closes on every path, including exceptions.
  3. 3Capping accumulated bytes protects memory from an unbounded or hostile response stream.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Reading a socket with connect and read timeouts — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code