public class TimeClientHandler implements CompletionHandler<Void, TimeClientHandler>, Runnable {
private AsynchronousSocketChannel asc;
private String host;
private int port;
private CountDownLatch latch;
public TimeClientHandler(String host, int port) {
this.host = host;
this.port = port;
try {
this.asc = AsynchronousSocketChannel.open();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
latch = new CountDownLatch(1);
asc.connect(new InetSocketAddress(host, port), this, this);
try {
latch.await();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
try {
asc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void completed(Void result, TimeClientHandler attachment) {
byte[] req = "Hi Server !".getBytes();
ByteBuffer writeBuffer = ByteBuffer.allocate(req.length);
writeBuffer.put(req);
writeBuffer.flip();
asc.write(writeBuffer, writeBuffer, new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer result, ByteBuffer buffer) {
if (buffer.hasRemaining()) {
asc.write(buffer, buffer, this);
} else {
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
asc.read(readBuffer, readBuffer, new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer result, ByteBuffer buffer) {
buffer.flip();
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
String body;
try {
body = new String(bytes, "UTF-8");
System.out.println("Now is : " + body);
latch.countDown();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
@Override
public void failed(Throwable exc, ByteBuffer attachment) {
try {
asc.close();
latch.countDown();
} catch (IOException e) {
}
}
});
}
}
@Override
public void failed(Throwable exc, ByteBuffer attachment) {
try {
asc.close();
latch.countDown();
} catch (IOException e) {
}
}
});
}
@Override
public void failed(Throwable exc, TimeClientHandler attachment) {
exc.printStackTrace();
try {
asc.close();
latch.countDown();
} catch (IOException e) {
e.printStackTrace();
}
}
}