欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Netty入门应用开发

程序员文章站 2022-06-05 18:45:13
...

使用netty开发一个实现以下功能的程序:客户端向服务端发送消息,服务端返回消息。

首先是服务端的代码:

public class NettyServer  {

    public static void main(String[] args) {
        new NettyServer().bind(8989);
    }
    public void bind(int port){
        /**
         *  配置服务端的NIO线程组,NioEventLoopGroup是个线程组
         *  这里创建两个的原因是:一个用于服务端接收客户端的连接
         *                    另一个用于进行SocketChannel的网络读写
         */
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        System.out.println("Server is starting on port : "+port+"...");
        try{
            //创建ServerBootstrap对象,它是Netty用于启动NIO服务端的辅助启动类,目的是降低服务端的开发复杂度
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup,workGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,1024)//配置NioServerSocketChannel的TCP参数
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {//绑定IO事件的处理类
                            socketChannel.pipeline().addLast(new TimeServerHandler());
                        }
                    });
            //绑定端口,同步等待成功,ChannelFuture主要用于异步操作的通知回调
            ChannelFuture f = b.bind(port).sync();//sync():同步阻塞方法
            //等待服务端监听端口关闭
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            //优雅退出,释放线程池资源
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

}
服务端IO事件处理类:

public class TimeServerHandler extends ChannelHandlerAdapter{
    @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,"UTF-8");
        System.out.println("The time server receive message is : "+body);
        String resp = "";
        if (body!=null){
            resp = "Server has received message that is : "+body;
        }else {
            resp = "Server has not received message...";
        }
        ByteBuf response = Unpooled.copiedBuffer(resp.getBytes());
        ctx.write(response);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();  //将消息发送队列中的消息全部写入到SocketChannel中发送给对方
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();//发生异常时,关闭ChannelHandlerContext
    }
}

客户端代码:

public class NettyClient {

    public static void main(String[] args) {
        int port = 8989;
        new NettyClient().connect(port,"127.0.0.1");
    }

    public void connect(int port,String host){
        //配置客户端NIO线程组
        NioEventLoopGroup 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 (InterruptedException e) {
            e.printStackTrace();
        }finally {
            //优雅退出,释放NIO线程组
            group.shutdownGracefully();
        }
    }
}

客户端IO处理类:

public class TimeClientHandler extends ChannelHandlerAdapter{
    private static final Logger logger = Logger
            .getLogger(TimeClientHandler.class.getName());
    private final ByteBuf buf;

    public TimeClientHandler() {
        byte[] req = "client is sending message...".getBytes();
        buf = Unpooled.buffer(req.length);
        buf.writeBytes(req);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(buf);
    }

    @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,"utf-8");
        System.out.println("接收到服务端的反馈为:"+body);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //释放资源
        logger.warning("Unexpected exception from downStream : "+cause.getMessage());
        ctx.close();
    }
}