Netty

优势
1.API使用简单,开发门槛低
2.功能强大,预置了多种编码功能,支持多种主流协议;
3.定制能力强,可以通过channelHandler对通信框架进行灵活地扩展;
4.性能高,通过与其他业界主流的NIO框架对比,netty的综合性能最优;
5.成熟、稳定,netty修复了已发现的所有jdk nio bug,业务开发人员不需要再为nio的bug而烦恼;

核心组件

Bootstrap、EvenLoop(Group)、Channel

Bootstrap:启动类,注方法类
EvenLoop:事件循环, 可以理解为一个线程
Channel:类似于Socket

在这里插入图片描述
事件和 ChannelHandler、ChannelPipeline

事件:把网络上法生的事情,和要做的事情包装成了事件
ChannelHandler:负责处理事件
ChannelPipeline:负责把ChannelHandler组织在一起(责任链模式)

ChannelFuture
出站操作,类似于future异步

代码

核心就是引擎这块,客户端,服务端万变不离其宗

客户端(固定的)

/**
 * 作者:yuyang
 * 类说明:基于Netty的客户端
 */
public class EchoClient {

    private final int port;
    private final String host;

    public EchoClient(int port, String host) {
        this.port = port;
        this.host = host;
    }

    public void start() throws InterruptedException {

        /*线程组*/
        EventLoopGroup group  = new NioEventLoopGroup();
        try {
            /*客户端启动必备*/
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)/*指定使用NIO的通信模式*/
                    .remoteAddress(new InetSocketAddress(host,port))/*指定服务器的IP地址和端口*/
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new EchoClientHandler());

                        }
                    });
            ChannelFuture f = b.connect().sync();/*异步连接到服务器,sync()会阻塞到完成*/
            f.channel().closeFuture().sync();/*阻塞当前线程,直到客户端的Channel被关闭*/
        } finally {
            group.shutdownGracefully().sync();

        }
    }

    public static void main(String[] args) throws InterruptedException {
        new EchoClient(9999,"127.0.0.1").start();
    }
}

客户端引擎

public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    /*读取到网络数据后进行业务处理*/
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        System.out.println("client Accept"+msg.toString(CharsetUtil.UTF_8));
        ctx.close();
    }

    /*channel活跃后,做业务处理*/
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer(
                "Hello,Netty",CharsetUtil.UTF_8));
    }
}

服务端(固定的)

/**
 * 作者:yuyang
 * 类说明:基于Netty的服务器
 */
public class EchoServer  {
    private static final Logger LOG = LoggerFactory.getLogger(EchoServer.class);
    private final int port;
    public EchoServer(int port) {
        this.port = port;
    }

    public static void main(String[] args) throws InterruptedException {
        int port = 9999;
        EchoServer echoServer = new EchoServer(port);
        LOG.info("服务器即将启动");
        echoServer.start();
        LOG.info("服务器关闭");
    }

    public void start() throws InterruptedException {
        final EchoServerHandler serverHandler = new EchoServerHandler();
        /*线程组*/
        EventLoopGroup group  = new NioEventLoopGroup();
        try {
            /*服务端启动必备*/
            ServerBootstrap b = new ServerBootstrap();
            b.group(group)
            .channel(NioServerSocketChannel.class)/*指定使用NIO的通信模式*/
            .localAddress(new InetSocketAddress(port))/*指定监听端口*/
                    //.childOption()
            //.handler();
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(serverHandler);
                }
            });
            ChannelFuture f = b.bind().sync();/*异步绑定到服务器,sync()会阻塞到完成*/
            f.channel().closeFuture().sync();/*阻塞当前线程,直到服务器的ServerChannel被关闭*/
        } finally {
            group.shutdownGracefully().sync();
        }
    }
}

服务端引擎

@ChannelHandler.Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf in = (ByteBuf)msg;
        System.out.println("Server accept: "+in.toString(CharsetUtil.UTF_8));

        ctx.writeAndFlush(in);
        ctx.close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}

相关推荐

  1. <span style='color:red;'>Netty</span>

    Netty

    2024-06-10 18:58:02      29 阅读
  2. <span style='color:red;'>Netty</span>

    Netty

    2024-06-10 18:58:02      32 阅读
  3. netty使用

    2024-06-10 18:58:02       55 阅读
  4. Netty学习

    2024-06-10 18:58:02       57 阅读
  5. Netty:AIO

    2024-06-10 18:58:02       29 阅读
  6. netty-学习

    2024-06-10 18:58:02       23 阅读
  7. Netty UDP

    2024-06-10 18:58:02       22 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-10 18:58:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-10 18:58:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-06-10 18:58:02       82 阅读
  4. Python语言-面向对象

    2024-06-10 18:58:02       91 阅读

热门阅读

  1. SpEL 表达式是什么?

    2024-06-10 18:58:02       26 阅读
  2. Spring (40)Spring Cloud和Spring Boot

    2024-06-10 18:58:02       33 阅读
  3. 独孤思维:做副业,万物皆可成为素材

    2024-06-10 18:58:02       25 阅读
  4. pdf分割为bmp

    2024-06-10 18:58:02       33 阅读
  5. 如何解决ArrayList缺陷

    2024-06-10 18:58:02       26 阅读
  6. python基础篇(日更中)

    2024-06-10 18:58:02       33 阅读
  7. NG32单片机GPIO口配置方式

    2024-06-10 18:58:02       31 阅读
  8. 2024-06-05 拷贝、函数、装饰器、迭代生成器

    2024-06-10 18:58:02       29 阅读