AsynchronousSocketChannel Echo Roundtrip

Run one echo roundtrip over AsynchronousSocketChannel completion handlers while the main thread parks on a CountDownLatch until callbacks land.

JavaData Fetching

Code

snippet
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;

public class AsyncEcho {

    public static void main(String[] args) throws Exception {
        AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open()
                .bind(new InetSocketAddress("127.0.0.1", 0));
        int port = ((InetSocketAddress) server.getLocalAddress()).getPort();
        CountDownLatch done = new CountDownLatch(1);

        // accept 的回调链:读回声、打印、关闭、放行主线程
        server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {
            @Override
            public void completed(AsynchronousSocketChannel channel, Void att) {
                ByteBuffer buffer = ByteBuffer.allocate(64);
                channel.read(buffer, null, new CompletionHandler<Integer, Void>() {
                    @Override
                    public void completed(Integer read, Void att) {
                        buffer.flip();
                        String received = new String(buffer.array(), 0, read, StandardCharsets.UTF_8);
                        System.out.println("echoed: " + received.trim());
                        try {
                            channel.close();
                        } catch (IOException ignored) {
                            // 连接收尾失败不影响演示
                        }
                        done.countDown();
                    }

                    @Override
                    public void failed(Throwable exc, Void att) {
                        done.countDown();
                    }
                });
            }

            @Override
            public void failed(Throwable exc, Void att) {
                done.countDown();
            }
        });

        // 客户端走同一套 AIO API:connect/write 返回 Future,get() 等完成
        AsynchronousSocketChannel client = AsynchronousSocketChannel.open();
        client.connect(new InetSocketAddress("127.0.0.1", port)).get();
        client.write(ByteBuffer.wrap("ping from client".getBytes(StandardCharsets.UTF_8))).get();

        done.await(); // 一次完整 roundtrip:write -> read 回调 -> countDown
        client.close();
        server.close();
    }
}

The code path

AsynchronousSocketChannel Echo Roundtrip comes down to the class AsyncEcho and the functions completed and failed.

Caveats

  • No dependencies section needed; the standard library is the whole story.

Using it

The main signature is public void completed(AsynchronousSocketChannel channel, Void att)

Look for the echoed: prefixes when the file runs; they tie each line to its step.

Execute the file and main walks through completed and failed, in that order.

Key statements

client.write(ByteBuffer.wrap("ping from client".getBytes(StandardCharsets.UTF_8))).get();
AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open()
        .bind(new InetSocketAddress("127.0.0.1", 0));
String received = new String(buffer.array(), 0, read, StandardCharsets.UTF_8);

FAQ

What does AsynchronousSocketChannel Echo Roundtrip print when run?
Run it as a complete program — the output lines carry labels such as `echoed:`.