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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Separate connect and read timeouts guard against both unreachable hosts and stalled mid-transfer peers.
- 2Try-with-resources guarantees the socket closes on every path, including exceptions.
- 3Capping accumulated bytes protects memory from an unbounded or hostile response stream.
Related explainers
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
Intermediate
6 steps
php
<?php final class RotatingFileLogger {
How a rotating file logger works in PHP
logging
file-rotation
io
Intermediate
9 steps
java
public final class EncodingDetector { public enum Encoding { UTF_8, UTF_16LE, UTF_16BE, UTF_32LE, UTF_32BE, ASCII, UNKNOWN
Detecting text encoding from raw bytes in Java
byte-manipulation
encoding-detection
bitwise-operations
Intermediate
8 steps
java
public final class ImportOrganizer { private static final Pattern IMPORT_LINE = Pattern.compile("^import\\s+(static\\s+)?([\\w.]+(?:\\.\\*)?)\\s*;\\s*$");
Sorting Java imports with a regex pass
regex
sorting
text-processing
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/reading-a-socket-with-connect-and-read-timeouts-explained-java-8be2/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.