【Netty权威指南学习笔记】Netty尝鲜开始

这篇博客是关于Netty权威指南的学习笔记,首先介绍了服务类的构建,然后详细阐述了一个简单服务端的实现过程,接着转向客户端的处理类讨论。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Netty权威指南学习笔记

服务类

public class TimeServer {


    public void bind(int port) throws Exception{
        /**
         * NioEventLoopGroup是个线程组,包含了一组NIO线程,实际上它们就是Rector线程组
         * 这里创建两个的原因: 一个用于服务端接收客户端的连接,一个用于进行SocketChannel的网络读写
         * */
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            /**
             * ServerBootstrap是Netty用于启动NIO服务端的辅助启动类,目的是降低服务端的开发复杂度。
             * */
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)// 相当于JDK中的ServerSocketChannel类
                    .option(ChannelOption.SO_BACKLOG, 1024)// 设置TCP参数
                    .childHandler(new ChildChannelHandler());// 绑定I/O事件的处理类(例如记录日志,编解码等)

            /**
             * 绑定完成后会返回一个ChannelFuture,类似于JDK中的java.util.concurrent.Future
             * 主要用于异步操作的通知回调
             * */
            ChannelFuture f = b.bind(port)// 绑定监听端口
                                .sync();// 调用同步阻塞方法,等待绑定完成;
            f.channel().closeFuture().sync();// 等待服务端链路关闭之后main函数才退出
        }catch (Exception e){
            e.printStackTrace();
            // 优雅的退出
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        int port = 7788;
        if(args != null && args.length > 0){
            try {
                port = Integer.valueOf(args[0]);
            }catch (Exception e){

            }
        }
        new TimeServer().bind(port);
    }

}

看看这是什么

public class ChildChannelHandler extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        socketChannel.pipeline().addLast(new TimeServerHandler());
    }
}

具体处理

public class TimeServerHandler extends ChannelHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        /**
         * ByteBuf类似于JDK中的java.nio.ByteBuffer
         * 通过 buf.readableBytes() 可以获取缓冲区可读的字节数
         * */
        ByteBuf buf = (ByteBuf) msg;
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);// 将缓冲区的字节数组复制到新的数组中

        String body = new String(req, CharsetUtils.Charset.UTF8.getName());
        log.info("the timeserver receive order : " + body);
        System.out.println("the timeserver receive order : " + body);

        String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ?
                new Date(System.currentTimeMillis()).toString() : "BAD ORDER";

        ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
        /**
         * 通过ChannelHandlerContext的write方法异步发送应答消息给客户端
         * */
        ctx.write(resp);
    }


    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        /**
         * 从性能角度考虑,为了防止频繁地唤醒Selector进行消息发送,Netty的write方法并不直接将消息写入SocketChannel中,
         * 调用write()只是把待发送的消息放到发送缓冲数组中,再通过调flush方法,将发送缓冲区中的消息全部写到SocketChannel中。
         * */
        ctx.flush();// 将消息发送队列中的消息写入到SocketChannel中发送给对方
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}

---以上一个简单的服务端完成


---客户端

public class TimeClient {

    public void connect(int port, String host) throws Exception{
        // 配置客户端NIO线程组
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new TimeClientHandler());
                        }
                    });

            ChannelFuture f = b.connect(host, port).sync();
            f.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            group.shutdownGracefully();
        }
    }


    public static void main(String[] args) throws Exception {
        int port = 7788;
        if(args != null && args.length > 0){
            try {
                port = Integer.valueOf(args[0]);
            }catch (Exception e){

            }
        }
        new TimeClient().connect(port, "127.0.0.1");
    }
}

处理类

public class TimeClientHandler extends ChannelHandlerAdapter {

    private final ByteBuf firstMessage;

    public TimeClientHandler() {
        byte[] req = "QUERY TIME ORDER".getBytes();
        firstMessage = Unpooled.buffer(req.length);
        firstMessage.writeBytes(req);
    }

    /**
     * 当客户端和服务器端TCP链路建立成功之后,Netty的NIO线程会调用channelActive方法
     * 调用ChannelHandlerContext.writeAndFlush()将请求消息发送给服务端。
     * */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(firstMessage);
    }

    /**
     * 当服务端返回应答消息时, channelRed方法被调用
     * */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        String body = new String(req, CharsetUtils.Charset.UTF8.getName());
        System.out.println("Nos is : " + body);

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("Unexcepted exception from downstream : " + cause.getMessage());
        ctx.close();
    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值