版权声明:本文为Zhang Phil原创文章,请不要转载! https://blog.csdn.net/zhangphil/article/details/88189548
Java新AIO/NIO2:以CompletionHandler实现AsynchronousSocketChannel客户端读操作
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.Future;
public class Client {
public static void main(String[] args) {
try {
Client client = new Client();
} catch (Exception e) {
e.printStackTrace();
}
}
public Client() throws Exception {
AsynchronousSocketChannel socketChannel = AsynchronousSocketChannel.open();
InetSocketAddress inetSocketAddress = new InetSocketAddress("localhost", 80);
Future<Void> connect = socketChannel.connect(inetSocketAddress);
while (!connect.isDone()) {
Thread.sleep(10);
}
System.out.println("建立连接" + socketChannel.getRemoteAddress());
ByteBuffer buffer = ByteBuffer.allocate(1024);
MyCompletionHandler completionHandler = new MyCompletionHandler();
socketChannel.read(buffer, buffer, completionHandler);
}
private class MyCompletionHandler implements CompletionHandler<Integer, ByteBuffer> {
@Override
public void completed(Integer result, ByteBuffer attachment) {
System.out.println("接收服务器数据:" + new String(attachment.array(), 0, result));
}
@Override
public void failed(Throwable t, ByteBuffer attachment) {
t.printStackTrace();
}
}
}