1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| package com.bai;
import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler;
public class AIOClient {
public static void main(String[] args) throws IOException {
final AsynchronousSocketChannel client = AsynchronousSocketChannel.open();
InetSocketAddress serverAddress = new InetSocketAddress("127.0.0.1", 8001);
CompletionHandler<Void, ? super Object> handler = new CompletionHandler<Void, Object>() {
@Override public void completed(Void result, Object attachment) { final ByteBuffer bb = ByteBuffer.allocate(1024); client.write(ByteBuffer.wrap("hello".getBytes()), null, new CompletionHandler<Integer, Object>() {
@Override public void completed(Integer result, Object attachment) { final ByteBuffer buffer = ByteBuffer.allocate(1024); client.read(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {
@Override public void completed(Integer result, ByteBuffer attachment) { buffer.flip(); System.out.println("In client: "+new String(buffer.array()));
}
@Override public void failed(Throwable exc, ByteBuffer attachment) { } }); }
@Override public void failed(Throwable exc, Object attachment) { } }); }
@Override public void failed(Throwable exc, Object attachment) { } };
client.connect(serverAddress, null, handler); while(true){ try { Thread.sleep(Integer.MAX_VALUE); } catch (InterruptedException e) { e.printStackTrace(); } } } }
|