SocketChannel Reads Until EOF
Loop read on a blocking SocketChannel until read() returns -1 for EOF, then echo back, with shutdownOutput closing the write half cleanly.
Code
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class EofLoop {
public static void main(String[] args) throws Exception {
ServerSocketChannel server = ServerSocketChannel.open()
.bind(new InetSocketAddress("127.0.0.1", 0));
int port = ((InetSocketAddress) server.getLocalAddress()).getPort();
ExecutorService worker = Executors.newSingleThreadExecutor();
worker.submit(() -> {
try (SocketChannel peer = server.accept()) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
int received = 0;
int read;
// blocking SocketChannel reads until EOF:read() 返回 -1 表示对端半关闭
while ((read = peer.read(buffer)) != -1) {
received += read;
}
buffer.flip();
String echoed = new String(buffer.array(), 0, received, StandardCharsets.UTF_8);
peer.write(ByteBuffer.wrap(("echo: " + echoed).getBytes(StandardCharsets.UTF_8)));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
try (SocketChannel client = SocketChannel.open(new InetSocketAddress("127.0.0.1", port))) {
client.write(ByteBuffer.wrap("hello eof loop".getBytes(StandardCharsets.UTF_8)));
client.shutdownOutput(); // 只关写半边:服务端 read 循环拿到 EOF 收尾
ByteBuffer reply = ByteBuffer.allocate(1024);
int replyLen = 0;
int r;
while ((r = client.read(reply)) != -1 && reply.hasRemaining()) {
replyLen += r;
}
reply.flip();
System.out.println(new String(reply.array(), 0, replyLen, StandardCharsets.UTF_8));
}
worker.shutdown();
server.close();
}
}What the code does
The working surface is the class EofLoop — everything else is wiring.
Iteration happens inside while ((read = peer.read(buffer)) != -1) — everything outside it runs once. The try-with-resources form guarantees each declared resource is closed even when the body throws. Invalid states are rejected up front: it throws UncheckedIOException instead of continuing with bad data.
Key statements
ExecutorService worker = Executors.newSingleThreadExecutor();
throw new UncheckedIOException(e);
received += read;
FAQ
- What happens if the preconditions do not hold?
- It throws `UncheckedIOException` before any real work runs — handle it at the call site or let it propagate deliberately.
- How do you run SocketChannel Reads Until EOF?
- Direct execution is enough; the script has no external requirements.
Report a problem with this exampleOpens a pre-filled issue on GitHub.