2 Haziran 2021 Çarşamba

AsynchronousServerSocketChannel Sınıfı - NIO

Giriş
Şu satırı dahil ederiz
import java.nio.channels.AsynchronousServerSocketChannel;
accept metodu - CompletionHandler
Şöyle yaparız
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;

public class TestServer {
  private AsynchronousServerSocketChannel channel;
  public TestServer(int port) {

    try {
      channel = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(port));
    } catch (IOException e) {
...
    }

    channel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {
      @Override
      public void completed(AsynchronousSocketChannel socket, Void attachment) {
        channel.accept(attachment, this);
        ByteBuffer byteBuffer = ByteBuffer.allocate(64);
        socket.read(byteBuffer);
        byteBuffer.flip();
        System.out.println(new String(byteBuffer.array()));
      }
      @Override
      public void failed(Throwable exc, Void attachment) {
        System.out.println("Failed to establish communication");
      }
    });
  }
}

Hiç yorum yok:

Yorum Gönder