← 中文资源

简体中文版本

SocketChannel 读到 EOF 的循环

阻塞 SocketChannel 的读循环以 -1 作为 EOF 信号,shutdownOutput 只关写半边让服务端读完收尾,回声写回后再关闭连接,半关闭语义清晰。

阅读英文原文

实现说明

底层就是类 EofLoop。 这个示例中仅有的重复出现在 while ((read = peer.read(buffer)) != -1) 里。资源声明在 try-with-resources 头部,任何退出路径都会自动关闭,无需 finally 块。代码不会带着坏状态静默继续,守卫一命中就抛 UncheckedIOException。

常见问题

前置条件不成立会发生什么?

在真正开工之前就会抛出 UncheckedIOException——请在调用点处理,或有意向上传播。

「SocketChannel 读到 EOF 的循环」这个示例怎么运行?

文件自包含:直接运行,没有需要预先安装的依赖。

核心语句

ExecutorService worker = Executors.newSingleThreadExecutor();
throw new UncheckedIOException(e);
received += read;

代码示例

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();
    }
}