您的位置:

Netty书籍推荐

一、Netty是什么

Netty是一个高性能、异步的NIO框架,基于Java NIO的特性进行封装。它的出现,使得基于NIO的开发变得更加简单,同时提高了性能和可靠性。在我们学习Netty之前,推荐阅读以下两本书籍:

二、《Netty权威指南》

《Netty权威指南》通俗易懂,适合入门学习。这本书旨在为使用Netty框架的开发人员提供一个全面的、深入的指南,涵盖了网络协议、异步编程和Netty API的所有方面。这本书分为七个部分,其中包括:Netty的架构和工作原理、Netty的基本组件和功能、网络协议的实现、数据处理、安全性、优化和扩展。下面是一个简单的Netty服务端的示例:

public class NettyServer {

    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new StringDecoder());
                            pipeline.addLast(new StringEncoder());
                            pipeline.addLast(new NettyServerHandler());
                        }
                    });

            ChannelFuture channelFuture = serverBootstrap.bind(6668).sync();

            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

class NettyServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println((String) msg);
        ctx.writeAndFlush("服务端已接收到消息");
    }
}

  

三、《深入分析Java Web技术内幕》

《深入分析Java Web技术内幕》是一本从Java基础知识到实际应用场景的详细阐述之书。在里面,关于Netty的介绍并不是非常详细,但是对于理解网络原理和协议处理有着重要的帮助。如果你在使用Netty过程中,遇到了一些网络协议的问题,这本书会给你提供新的思路。下面是一个简单的HTTP服务端的示例:

public class HttpServer {

    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap()
                    .group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new HttpServerCodec());
                            pipeline.addLast(new HttpObjectAggregator(1024 * 1024));
                            pipeline.addLast(new HttpServerHandler());
                        }
                    });
            ChannelFuture channelFuture = serverBootstrap.bind(8888).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

class HttpServerHandler extends SimpleChannelInboundHandler
    {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
        System.out.println(msg.toString());
        ByteBuf content = Unpooled.copiedBuffer("服务端已接收到消息", CharsetUtil.UTF_8);
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
        ctx.writeAndFlush(response);
    }
}

   
  

四、《Netty实战》

《Netty实战》是一个循序渐进的指南,适合开发人员逐步掌握Netty框架,并在实际应用中使用。该书覆盖了Netty网络编程的所有不同方面,包括:使用ByteBuf进行编解码、使用ChannelHandler实现协议处理、使用EventLoop执行异步I/O操作以及使用Netty构建客户端和服务端。下面是一个简单的Netty客户端的示例:

public class NettyClient {

    public static void main(String[] args) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new StringDecoder());
                            pipeline.addLast(new StringEncoder());
                            pipeline.addLast(new NettyClientHandler());
                        }
                    });
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 6668).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
}

class NettyClientHandler extends SimpleChannelInboundHandler
    {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush("客户端发送消息");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println(msg);
    }
}