SocketException
JavaERRORNotableNetwork
Socket operation failed — connection broken or refused
Quick Answer
Set SO_TIMEOUT to prevent hanging indefinitely, and implement retry with exponential back-off.
What this means
Thrown when a socket operation fails — connection reset by peer, refused, or socket closed while blocking.
Why it happens
- 1Remote server closed connection mid-transfer
- 2Firewall silently dropped the TCP connection
Fix
Set socket timeout
Set socket timeout
Socket s = new Socket(); s.setSoTimeout(5000); s.connect(new InetSocketAddress(host, port), 3000);
Why this works
SO_TIMEOUT throws SocketTimeoutException on blocked reads instead of hanging forever.
Code examples
Catch connection resetjava
try {
in.read(buf);
} catch (SocketException e) {
log.warn("Connection reset: {}", e.getMessage());
}HttpClient timeoutjava
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.build();Retry with back-offjava
int delay = 500;
for (int i = 0; i < 3; i++, delay *= 2) {
try { return call(); }
catch (SocketException e) { Thread.sleep(delay); }
}Same error in other languages
Sources
Official documentation ↗
Java SE Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev