一、Netty的定义

Netty是一个基于Java NIO的网络编程框架,提供了一套高效的、事件驱动的异步网络通信机制。简化了网络应用程序的开发过程,提供了可靠的、高性能的网络传输

二、Netty的特点是什么

  1. 异步和事件驱动:Netty使用异步的、非阻塞的I/O模型,通过事件驱动的方式处理网络操作。Netty能够高效地处理并发连接和大量的并发请求。
  2. 高性能:Netty采用了一系列优化策略,如零拷贝技术、内存池和可定制的线程模型等,以提供出色的性能和吞吐量。能处理高负载和大规模并发
  3. 多协议支持:Netty提供了丰富的协议支持,包括常用的网络协议(如HTTP、WebSocket、TCP和UDP)以及自定义协议。具备灵活的编解码器和处理器,简化了协议的实现和交互。
  4. 可扩展和灵活:Netty的架构和组件设计具有高度的可扩展性和灵活性。它提供了一组可重用的组件,可以根据应用需求进行定制和扩展。
  5. 安全性:Netty提供了强大的安全性支持,包括SSL/TLS的集成、加密和认证等机制,可以保护网络通信的安全性。
  6. 易于使用和学习:提供了清晰简洁的API和文档,易于使用和学习。它还具有丰富的示例和教程,帮助开发人员快速上手和构建可靠的网络应用。

三、Netty的架构图

四、这里我们主要讲client端,server端,和channel端

客户端代码

EventLoopGroup group = new NioEventLoopGroup();

Bootstrap b = new Bootstrap();

b.group(group).channel(NioSocketChannel.class);

b.handler(new ChannelInitializer<Channel>() {

@Override

protected void initChannel(Channel ch) throws Exception {

ChannelPipeline pipeline = ch.pipeline();

pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));

pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));

pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));

pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));

pipeline.addLast("handler", new TcpClientHandler());

}

});

b.option(ChannelOption.SO_KEEPALIVE, true);

// 发送消息

Channel channel = b.connect(host, port).sync().channel();

channel.writeAndFlush(msg).sync();

服务器端代码

ServerBootstrap b = new ServerBootstrap();

b.group(bossGroup, workerGroup);

// TCP channel

b.channel(NioServerSocketChannel.class);

b.childHandler(new ChannelInitializer<SocketChannel>() {

@Override

public void initChannel(SocketChannel ch) throws Exception {

ChannelPipeline pipeline = ch.pipeline();

pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));

pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));

pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));

pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));

pipeline.addLast(new TcpServerHandler());

}

});

b.bind(IP, PORT).sync();

LOG.info("TCP服务器已启动");

缓存channel通道SimpleChannelInboundHandler

@Override

protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {

LOG.info("接收到消息:" + msg);

// 接收到消息后再次发送消息

ctx.channel().writeAndFlush("已经收到消息:" + msg);

}

更多推荐