Netty - Starting from Example

118 阅读1分钟
NioEventLoopGroup group = new NioEventLoopGroup();
ServerBootstrap bootstrap = new ServerBootstrap();

bootstrap.group(group)
         .channel(NioServerSocketChannel.class)
         .childHanlder(new SimpleChannelInboundHandler<ByteBuf>(){
               @Override
               protected void channelRead0(ChannelHandlerContext ctx, ByteBuf bytebuf) throws Exception{
                   System.out.println("Received Data");
               }
          });
ChannelFuture future=bootstrap.bind(new InetSocketAddress(8080));
future.addListener(new ChannelFutureListener(){
    @Override
    public void operationComplete(ChannelFuture channelFuture) throws Exception{
        if(channelFuture.isSuccess){
             System.out.println("Server bound");
        }else{
             System.err.println("Bound attempt failed");
        }
    }

});

Internally, the bootstrap bind will call AbstractBootStrap.doBind()method.

Inside doBind() method, few steps:

  1. initAndRegister(), this is the one which actually performs registering the selector to channel.
  2. doBind0(), this will propogate the bind action till the pre-set head ctx, which internally call unsafe.bind() method to bind the actual binding.