我是靠谱客的博主 威武未来,最近开发中收集的这篇文章主要介绍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();
    }
}


最后

以上就是威武未来为你收集整理的Netty入门应用开发的全部内容,希望文章能够帮你解决Netty入门应用开发所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(47)

评论列表共有 0 条评论

立即
投稿
返回
顶部