Netty入门应用开发

使用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();
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值