netty知识分享 (一):

381 阅读2分钟

      众所周知,netty是一个非常优雅的NIO框架,封装了复杂的java nio底层实现,并且单节点可以支撑百万级别的连接,无论从使用还是性能方面上看都是非常强大的。在圈内应用也非常的广泛,比如如雷贯耳的hadoop、dubbo、大型的游戏后台,都可以看到netty的影子,反正学习netty,好处那是大大的有,废话不多说,我们直接撸代码。

在撸代码之前,我们要在maven中配置netty的依赖

<dependencies>
    <dependency>
        <groupId>io.netty</groupId>
        <artifactId>netty-all</artifactId>
        <version>4.1.50.Final</version>
    </dependency>
</dependencies>

先上一段客户端和服务端通信的demo:

server端

public class Server {
    public static void main(String[] args) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try{
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup,workGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,128)
                    .option(ChannelOption.SO_KEEPALIVE,true)
                    .childHandler(new           ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast("encoder",new StringEncoder());
                            pipeline.addLast("decoder",new StringDecoder());
                            pipeline.addLast(new MyHandler());
                        }
                    });
            ChannelFuture future = bootstrap.bind(1000).sync();

            System.out.println("服务器启动...");

            future.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }

    }
}

服务端启动的大致步骤:

  1. 首先创建两个EventLoopGroup对象,分别为bossGroup、workGroup。

  2. 通过ServerBootstrap服务端引导类,来完成NioServerSocketChannel的创建

  3. 然后绑定1000端口

实现自己的handler:

public class MyHandler extends SimpleChannelInboundHandler<String> {
    protected void channelRead0(ChannelHandlerContext ctx, String o) throws Exception {
        System.out.println("channelRead0 .....");
        System.out.println(o);
        ctx.writeAndFlush("Server...");
    }

    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("chanelActive.....");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//        super.exceptionCaught(ctx, cause);
        System.out.println(cause.getMessage());
        ctx.close();
    }
}

完成自定义的handler非常简单,我们只需要来继承SimpleChannelInboundHandler类,然后可以再channelRead0方法中完成自己的实现即可

客户端:

public class Client {
    public static void main(String[] args) throws Exception{
        NioEventLoopGroup group = new NioEventLoopGroup();
        try{
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast("decoder", new StringDecoder());
                            pipeline.addLast("encoder",new StringEncoder());
                            pipeline.addLast(new ClintHandler());
                        }
                    });
            ChannelFuture future = bootstrap.connect("localhost", 1000).sync();

            future.channel().closeFuture().sync();
        }finally {
            group.shutdownGracefully();
        }
    }
}

客户端启动的大致步骤:

1、首先创建一个EventLoopGroup对象group。

2、通过Bootstrap服务端引导类,来完成NioSocketChannel的创建

3、然后连接服务器所在的ip 以及 1000端口号

客户端handler实现:

public class ClintHandler extends SimpleChannelInboundHandler<String> {

    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        System.out.println("客户端接收到信息 :" + s);
    }

    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("chanelActive.....");
        ctx.writeAndFlush("哈哈哈");
    }
}

具体的细节我们会在后面的章节中细细道来,今天我们只需要将我们的服务器和客户端运行起来,并且打印出我们的消息即可

bigo...

服务端运行结果:

客户端运行接口:

大功告成,出现这样的结果,你就可以去洗洗睡了

万事开头难,切行切珍惜,我是圈内小哥,本章完

感觉不错可以关注我哦,后面我会讲解netty的源码及原理,反正就是精彩不断