目录
Netty is an asynchronous event-driven network application framework
for rapid development of maintainable high performance protocol servers & clients.
Netty 是一个异步的、基于事件驱动的网络应用框架,用于快速开发可维护、高性能的网络服务器和客户端。用一句简单的话来说就是:Netty封装了JDK的NIO,让你用得更爽,你不用再写一大堆复杂的代码了。
Netty 是一个基于NIO的客户、服务器端的编程框架,使用Netty 可以确保你快速和简单的开发出一个网络应用,例如实现了某种协议的客户、服务端应用。Netty相当于简化和流线化了网络应用的编程开发过程,例如:基于TCP和UDP的socket服务开发。

Netty 在 Java 网络应用框架中的地位就好比:Spring 框架在 JavaEE 开发中的地位
以下的框架都使用了 Netty,因为它们有网络通信需求!
开发一个简单的服务器端和客户端
- <dependency>
- <groupId>io.nettygroupId>
- <artifactId>netty-allartifactId>
- <version>4.1.39.Finalversion>
- dependency>
- public class HelloServer {
- public static void main(String[] args) {
-
- new ServerBootstrap()
- //1 创建NioEventLoopGroup,可以简单理解为线程池+Selector
- .group(new NioEventLoopGroup())
- //2 选择服务Socket实现类,其中NioServerSocketChannel表示基于NIO的服务端实现
- .channel(NioServerSocketChannel.class)
- //3 添加的处理器都是给SocketChannel用的,而不是给ServerSocketChannel
- .childHandler(new ChannelInitializer
() { - protected void initChannel(NioSocketChannel ch) throws Exception {
- //5 SocketChannel的处理器,解码ByteBuffer==>String
- ch.pipeline().addLast(new StringDecoder());
- //6 SocketChannel的业务处理器。使用上一个处理器的处理结果
- ch.pipeline().addLast(new SimpleChannelInboundHandler
() { - protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
- System.out.println(s);
- }
- });
- }
- })
- .bind(8080);//4 绑定的端口
- }
- }
- public class HelloClient {
- public static void main(String[] args) throws InterruptedException {
- new Bootstrap()
- //1 创建NioEventLoopGroup通Server
- .group(new NioEventLoopGroup())
- //2 创建客户Socket实现类,NioSocketChannel表示基于NIO的客户端实现
- .channel(NioSocketChannel.class)
- //3 添加SocketChannel的处理器,ChannelInitializer处理器(仅执行一次),
- // 它的作用是待客户端SocketChannel建立连接以后,执行initChannel以便添加更多的处理器
- .handler(new ChannelInitializer
() { - protected void initChannel(Channel ch) throws Exception {
- //8
- ch.pipeline().addLast(new StringEncoder());
- }
- })
- //4 指定要连接的服务器和端口
- .connect("127.0.0.1",8080)
- //5 Netty中的很多方法都是异步的,如connet,这时需要使用sync方法等待connect建立连接完毕
- .sync()
- //6获取channel对象,它即为通道抽象它可以进行读写操作
- .channel()
- //7 写入消息并清空缓冲区
- .writeAndFlush(new Date()+":hello word!");
- }
- }
