2 Haziran 2017 Cuma

AsynchronousSocketChannel Sınıfı - NIO

Giriş
Şu satırı dahil ederiz.
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
connect metodu - InetSocketAddress
Şöyle yaparız.
Future<Void> futureConnect = channel.connect(
  new InetSocketAddress("www.yahoo.com", 80));
// wait until connected
futureConnect.get();
connect metodu - InetSocketAddress + CompletionHandler
Şöyle yaparız.
channel.connect(new InetSocketAddress("www.yahoo.com", 80),
  null, new CompletionHandler<Void, Object>() {
    @Override
    public void completed(Void result, Object attachment) {
      ...
    }
    @Override
    public void failed(Throwable exc, Object attachment) {
      ...
    }
});
close metodu
Şöyle yaparız.
channel.close();
open metodu
Şöyle yaparız.
AsynchronousSocketChannel channel = AsynchronousSocketChannel.open();
read metodu - ByteBuffer
Şöyle yaparız.
ByteBuffer bufferRead = ByteBuffer.allocate(23);
Future<Integer> futureRead = channel.read(bufferRead);
// wait ...
Integer resultRead = futureRead.get();
read metodu - ByteBuffer + CompletionHandler
Şöyle yaparız.
ByteBuffer buffer = ByteBuffer.allocate(23);

channel.read(buffer, null, new CompletionHandler<Integer, Object>() {
  @Override
  public void completed(Integer result, Object attachment) {
    System.out.println(new String(buffer.array()));
    ...
  }
  @Override
  public void failed(Throwable exc, Object attachment) {
    ...
  }
});
write metodu - ByteBuffer
Şöyle yaparız.
ByteBuffer buffer = ...
Future<Integer> futureWrite = channel.write(buffer);
// wait until all data is written
Integer resultWrite = futureWrite.get();
write metodu - ByteBuffer + CompletionHandler
Şöyle yaparız.
ByteBuffer buffer = ...;
channel.write(buffer, null, new CompletionHandler<Integer, Object>() {
  @Override
  public void completed(Integer result, Object attachment) {
    ...
  }
  @Override
  public void failed(Throwable exc, Object attachment) {
    ...
  }
});

Hiç yorum yok:

Yorum Gönder