Socket Half Close With shutdownOutput
shutdownOutput closes only the write direction: the peer sees a clean EOF, finishes its read loop, and can still send its final reply back.
Code
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
public class HalfCloseEcho {
public static void main(String[] args) throws Exception {
try (ServerSocket server = new ServerSocket(0)) {
Thread responder = new Thread(() -> {
try (Socket conn = server.accept()) {
InputStream in = conn.getInputStream();
byte[] buffer = new byte[256];
int read;
// shutdownOutput 后对端 read() 返回 -1,而不是无限等待
while ((read = in.read(buffer)) != -1) {
System.out.println("got: "
+ new String(buffer, 0, read, StandardCharsets.UTF_8));
}
// EOF 之后仍能写回结果:这是半关闭的核心收益
OutputStream out = conn.getOutputStream();
out.write("done".getBytes(StandardCharsets.UTF_8));
out.flush();
} catch (Exception e) {
e.printStackTrace();
}
});
responder.start();
try (Socket client = new Socket("localhost", server.getLocalPort())) {
OutputStream out = client.getOutputStream();
out.write("ping".getBytes(StandardCharsets.UTF_8));
out.write("pong".getBytes(StandardCharsets.UTF_8));
// 只关写方向:告诉服务端数据发完了,读方向保持打开
client.shutdownOutput();
InputStream in = client.getInputStream();
byte[] reply = in.readAllBytes();
System.out.println("reply: " + new String(reply, StandardCharsets.UTF_8));
}
responder.join(5000);
}
}
}Mapping the execution
Structurally, expect the class HalfCloseEcho and nothing else.
The loop while ((read = in.read(buffer)) != -1) is the only repeated construct. try-with-resources closes each declared resource automatically on every exit path.
Points of care
- Nothing but the language toolchain itself has to be present beforehand.
Applying it
The file’s steps show up in the output as got:, reply:.
Statements that matter
out.write("done".getBytes(StandardCharsets.UTF_8));
Interactive Tools for This Topic
FAQ
- What does Socket Half Close With shutdownOutput print when run?
- No setup needed: run the file and look for labeled lines like `got:`, `reply:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.