Netty

作者: haha_writing | 来源:发表于2021-03-31 09:10 被阅读0次

    概述

    Netty是一款用于快速开发高性能网络应用程序的Java开源框架。它不仅是接口和类的集合,还定义了一种架构模型以及一套丰富的设计模式。使用Netty,使得创建可扩展,健壮的网络程序变得更为容易。

    Netty的定义

    Netty是一款异步的事件驱动的网络应用程序框架,支持快速的开发可维护的高性能的面向协议的服务器和客户端。

    Netty的引用

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

    Netty的核心组件

    Bootstrap启动类

    Bootstrap启动类是Netty提供的一个便利的工厂类,可以通过它来完成Netty的客户端或服务器端的Netty组件的组装和Netty程序的初始化。在Netty中,有BootStrap和ServerBootStrap两个启动类,分别应用于客户端和服务端。

    EventLoop

    Netty中的EventLoop是一个处理事件的机制。当一个事件发生时,他们会将其传递给相应的event handler。

    EventLoopGroup

    EventLoopGroup指的是一组EventLoops,它们共享一些资源。

    Channel

    Channel是Java NIO的一个基本构造。它代表一个到实体(如一个硬件设备,一个文件,一个网络套接字或者一个能够执行一个或者多个不同的IO操作的程序组件)的开放连接,如读操作或写操作。常用的Channel是SocketChannel。

    ChannelHandler

    ChannelHandler用来处理数据,包含两个接口ChannelInboundHandler,ChannelOutboundHandler。Netty引入了编码和解码的概念。解码指的是在ChannelInboundHandler将字节转换为Java对象。而编码指的是将返回的Java对象转换为字节。

    ChannelPipeline

    ChannelPipeline是Netty中的核心概念。每一个SocketChannel包含一个ChannelPipeline。ChannelPipeline包含一系列ChannelHandler实例。

    回调

    一个回调其实就是一个方法。

    Future

    Future提供了另一种在操作完成时通知应用程序的方式。Netty提供了自己的ChannelFuture,用于在执行异步操作的时候使用。

    示例代码

    创建ChannelHandler

    public class HelloServerHandler extends ChannelInboundHandlerAdapter {
    
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            ByteBuf inBuffer = (ByteBuf) msg;
    
            String received = inBuffer.toString(CharsetUtil.UTF_8);
            System.out.println("Server received: " + received);
    
            ctx.write(Unpooled.copiedBuffer("Hello " + received, CharsetUtil.UTF_8));
        }
    
        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
            ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
                    .addListener(ChannelFutureListener.CLOSE);
        }
    
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();
            ctx.close();
        }
    }
    

    创建TCPServer

    //第一步,创建一个EventLoopGroup
    EventLoopGroup group = new NioEventLoopGroup(); 
    
    try{
        //第二步,创建一个ServerBootStrap。
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(group);
        serverBootstrap.channel(NioServerSocketChannel.class);
        serverBootstrap.localAddress(new InetSocketAddress("localhost", 9999));
    
        serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                socketChannel.pipeline().addLast(new HelloServerHandler());
            }
        });
        ChannelFuture channelFuture = serverBootstrap.bind().sync();
        channelFuture.channel().closeFuture().sync();
    } catch(Exception e){
        e.printStackTrace();
    } finally {
        group.shutdownGracefully().sync();
    }
    
    

    创建Client

    EventLoopGroup group = new NioEventLoopGroup();
    try{
        Bootstrap clientBootstrap = new Bootstrap();
    
        clientBootstrap.group(group);
        clientBootstrap.channel(NioSocketChannel.class);
        clientBootstrap.remoteAddress(new InetSocketAddress("localhost", 9999));
        clientBootstrap.handler(new ChannelInitializer<SocketChannel>() {
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                socketChannel.pipeline().addLast(new ClientHandler());
            }
        });
        ChannelFuture channelFuture = clientBootstrap.connect().sync();
        channelFuture.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully().sync();
    }
    

    相关文章

      网友评论

          本文标题:Netty

          本文链接:https://www.haomeiwen.com/subject/vnxlbktx.html