实现说明
活动部件是类 HalfCloseEcho。
文件的主干是一个循环——while ((read = in.read(buffer)) != -1)。不需要 finally——try 头部声明的资源按相反顺序自行关闭。
使用要点
- 演示输出是带标签的(
got:、reply:),每个操作都会留下自己的一行标注。
常见问题
运行「shutdownOutput 半关闭套接字」会打印什么?
整个文件跑完,输出行以 got:、reply: 这类前缀开头。
核心语句
out.write("done".getBytes(StandardCharsets.UTF_8));
代码示例
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);
}
}
}