实现说明
逻辑集中在类 AsyncEcho和函数 completed、failed里。
使用要点
- 每一步打印都带着自己的标签:
echoed:。 main的演示流程是completed、failed——跑一遍文件,这条流程从头到尾可见。
常见问题
运行「AsynchronousSocketChannel 回声往返」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 echoed: 这类标签。
主要签名是 public void completed(AsynchronousSocketChannel channel, Void att)
核心语句
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);
代码示例
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();
}
}