4 Haziran 2018 Pazartesi

Netty Channels

Channel Arayüzü
Giriş
Şu satırı dahil ederiz.
import io.netty.channel.Channel;
Socket ile aynı aynı anlama gelir. Açıklaması şöyle.
All methods on a Channel fall into two categories:
1.A simple attribute method that (synchronously) provides information about the channel itself.
2. I/O operations like bind, disconnect, or write.
All methods in category #2 are asynchronous* and they all return a ChannelFuture which is a  deferred result, meaning that it is a container for a result that is not known yet, but through      which the result will be delivered when it is available.
Bir başka açıklama şöyle
A channel is a connection to a network socket, which uses its I/O capabilities (such as read, write, connect, and bind) to communicate. A channel provides the following to the developer.
- The current state of the channel (e.g. is it open? is it connected?)
- The configuration parameters of the channel (e.g. receive buffer size)
- The I/O operations that the channel supports (e.g. read, write, connect, and bind)
- The ChannelPipeline which handles all I/O events and requests associated with the channel.
constructor
Şöyle yaparız.
Bootstrap b = new Bootstrap();

String host = ...; int port = ...;
b.group(new NioEventLoopGroup()).channel(NioSocketChannel.class)
  .remoteAddress(host, port).handler(new TelnetClientInitializer());
Channel ch = b.connect().sync().channel();
closeFuture metodu
Channel kapanınca tetiklenen ChannelFuture döner. Şöyle yaparız.
channel.closeFuture().sync();
eventLoop metodu
Şöyle yaparız.
channel.eventLoop().schedule(this, 100, MILLISECONDS); 
remoteAddress metodu
java.net.SocketAddress döner. Şöyle yaparız.
String remoteAddress = ctx.channel().remoteAddress().toString();
Şöyle yaparız.
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
  System.out.println(ctx.channel().remoteAddress()+"->Server :"+ msg.toString());
  ...
}
write metodu
Şöyle yaparız.
ChannelFuture f= null;
String str = ...;
f= ch.write(str);
writeAndFlush metodu
Örnek
nio.ByteBuffer göndermek için şöyle yaparız.
ByteBuffer buf = ...;

final ChannelFuture f = ch.writeAndFlush(buf);
Örnek
Şöyle yaparız.
ChannelFuture future = bootstrap.connect(hostAddress).await();
future.channel().writeAndFlush(buffer);
ChannelFuture Sınıfı
Açıklaması şöyle
Netty’s channel operations are asynchronous; i.e. they return immediately without a guarantee that it completed. The most logical question at this point is, “How to I ensure that something runs after this task completes and not before?” To make this possible, all asynchronous methods in Netty return a ChannelFuture instance. This class has methods to pipe other tasks upon completion to ensure tasks execute one after the other, but in a non-blocking manner.
addListener metodu

addListeners metodu
Örnek ver

await metodu
sync() ile farkının açıklaması şöyle.
The difference is indeed sync() will rethrow the failure if this future failed, while await() will not (and if you need the exception, you need to ask for it to the future objet using cause() method.
awaitUninterruptibly metodu
Örnek ver

cause metodu
Şöyle yaparız.
channelFuture.cause().printStackTrace();
channel metodu
Channel nesnesini döner.

isSuccess metodu
Şöyle yaparız.
private void doConnect() {
  Bootstrap b = ...;
  b.connect().addListener((ChannelFuture f) -> {
    if (!f.isSuccess()) {
      long nextRetryDelay = nextRetryDelay(...);
      f.channel().eventLoop().schedule(nextRetryDelay, ..., () -> {
        doConnect();
      }); // or you can give up at some point by just doing nothing.
    }
  });
}
removeListener metodu
Örnek ver

removeListeners metodu
Örnek ver

sync metodu
Future nesnesinin bitmesini bekler. Şöyle yaparız.
f = b.connect(host, port).sync();
DatagramChannel Sınıfı
joinGroup metodu
Şöyle yaparız.
ChannelFuture future = bootstrap.bind("192.168.10.1", PORT).await();
future = ((DatagramChannel) future.channel())
  .joinGroup(MULTICAST_ADDRESS, NetworkInterface.getByName("..."), null)
  .await();
EmbeddedChannel Sınıfı
Netty Unit Test yazısına taşıdım

NioServerSocketChannel Sınıfı
Giriş

Şu satırı dahil ederiz.
import io.netty.channel.socket.nio.NioServerSocketChannel;
Bağlantı accept() etmek için kullanılır.
Örnek
Şöyle yaparız.
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup(threadCount);
try {
  ServerBootstrap b = new ServerBootstrap();
  b.group(bossGroup, workerGroup)
   .channel(NioServerSocketChannel.class)
   .childHandler(new ChannelInitializer<SocketChannel>() {
     @Override
     public void initChannel(SocketChannel ch) throws Exception {
       ch.pipeline().addLast(new EchoServerComputeHandler());
     }
   })
   .option(ChannelOption.SO_BACKLOG, 128)          
   .childOption(ChannelOption.SO_KEEPALIVE, true); 

   ChannelFuture f = b.bind(port).sync(); 

   f.channel().closeFuture().sync();
} finally {
  workerGroup.shutdownGracefully();
  bossGroup.shutdownGracefully();
}
constructor - ServerSocketChannel 
Şöyle yaparız.

NioSocketChannel Sınıfı
Giriş
Şu satırı dahil ederiz.
import io.netty.channel.socket.nio.NioSocketChannel;
SocketChannel arayüzünden kalıtır

SocketChannel Arayüzü
Giriş
Şu satırı dahil ederiz.
Java'da da aynı isimli bir sınıf var. Dikkatli olmak lazım.
import io.netty.channel.socket.SocketChannel;

Hiç yorum yok:

Yorum Gönder