Netty是一个高性能 事件驱动的异步的非堵塞的IO(NIO)框架,用于创建TCP等底层的链接,基于Netty能够创建高性能的Http服务器。
一、首先来复习下非堵塞IO(NIO)
NIO这个库是在JDK1.4中才引入的。NIO和IO有相同的做用和目的,但实现方式不一样,NIO主要用到的是块,因此NIO的效率要比IO高不少。
在Java API中提供了两套NIO,一套是针对标准输入输出NIO,另外一套就是网络编程NIO。
*Buffer和Channel是标准NIO中的核心对象*
Channel是对原IO中流的模拟,任何来源和目的数据都必须经过一个Channel对象。一个Buffer实质上是一个容器对象,发给Channel的全部对象都必须先放到Buffer中;一样的,从Channel中读取的任何数据都要读到Buffer中。javascript
网络编程NIO中还有一个核心对象Selector,它能够注册到不少个Channel上,监听各个Channel上发生的事件,而且可以根据事件状况决定Channel读写。这样,经过一个线程管理多个Channel,就能够处理大量网络链接了。java
Selector 就是注册对各类 I/O 事件兴趣的地方,并且当那些事件发生时,就是这个对象告诉你所发生的事件。
Selector selector = Selector.open(); //建立一个selector
为了能让Channel和Selector配合使用,咱们须要把Channel注册到Selector上。经过调用channel.register()方法来实现注册:
channel.configureBlocking(false); //设置成异步IO
SelectionKey key =channel.register(selector,SelectionKey.OP_READ); //对所关心的事件进行注册(connet,accept,read,write)
SelectionKey 表明这个通道在此 Selector 上的这个注册。编程
二、异步
CallBack:回调是异步处理常常用到的编程模式,回调函数一般被绑定到一个方法上,而且在方法完成以后才执行,这种处理方式在javascript当中获得了充分的运用。回调给咱们带来的难题是当一个问题处理过程当中涉及不少回调时,代码是很难读的。
Futures:Futures是一种抽象,它表明一个事情的执行过程当中的一些关键点,咱们经过Future就能够知道任务的执行状况,好比当任务没完成时咱们能够作一些其它事情。它给咱们带来的难题是咱们须要去判断future的值来肯定任务的执行状态。
三、netty到底怎么工做的呢?
直接来看个最简单的实例bootstrap
服务器端服务器
public class EchoServer { private final static int port = 8007; public void start() throws InterruptedException{ ServerBootstrap bootstrap = new ServerBootstrap(); //引导辅助程序 EventLoopGroup group = new NioEventLoopGroup(); //经过nio的方式接受链接和处理链接 try { bootstrap.group(group) .channel(NioServerSocketChannel.class) //设置nio类型的channel .localAddress(new InetSocketAddress(port)) //设置监听端口 .childHandler(new ChannelInitializer<SocketChannel>() { //有链接到达时会建立一个channel // pipline 管理channel中的handler,在channel队列中添加一个handler来处理业务 @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("myHandler", new EchoServerHandler()); //ch.pipeline().addLast("idleStateHandler",new IdleStateHandler(0, 0, 180)); } }); ChannelFuture future = bootstrap.bind().sync(); //配置完成,绑定server,并经过sync同步方法阻塞直到绑定成功 System.out.println(EchoServer.class.getName() + " started and listen on " + future.channel().localAddress()); future.channel().closeFuture().sync(); //应用程序会一直等待,直到channel关闭 } catch (Exception e) { e.getMessage(); }finally { group.shutdownGracefully().sync(); } }
建立一个ServerBootstrap实例网络
建立一个EventLoopGroup来处理各类事件,如处理连接请求,发送接收数据等。框架
定义本地InetSocketAddress( port)好让Server绑定异步
建立childHandler来处理每个连接请求ide
全部准备好以后调用ServerBootstrap.bind()方法绑定Server函数
handler 处理核心业务
@Sharable //注解@Sharable可让它在channels间共享 public class EchoServerHandler extends ChannelInboundHandlerAdapter{ @Override public void channelRead(ChannelHandlerContext ctx,Object msg) throws Exception { ByteBuf buf = ctx.alloc().buffer(); buf.writeBytes("Hello World".getBytes()); ctx.write(buf); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } }
客户端 链接
public class EchoClient { private final int port; private final String hostIp; public EchoClient(int port, String hostIp) { this.port = port; this.hostIp = hostIp; } public void start() throws InterruptedException { Bootstrap bootstrap = new Bootstrap(); EventLoopGroup group = new NioEventLoopGroup(); try { bootstrap.group(group).channel(NioSocketChannel.class) .remoteAddress(new InetSocketAddress(hostIp, port)) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new EchoClientHandler()); } }); ChannelFuture future = bootstrap.connect().sync(); future.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { System.out.println("client connected"); } else { System.out.println("server attemp failed"); future.cause().printStackTrace(); } } }); future.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { group.shutdownGracefully().sync(); } }
客户端handler
@Sharable public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf>{ /** *此方法会在链接到服务器后被调用 * */ public void channelActive(ChannelHandlerContext ctx) { System.out.println("Netty rocks!"); ctx.write(Unpooled.copiedBuffer("Netty rocks!", CharsetUtil.UTF_8)); } /** * 接收到服务器数据时调用 */ @Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception { System.out.println("Client received: " + ByteBufUtil.hexDump(msg.readBytes(msg.readableBytes()))); } /** *捕捉到异常 * */ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } }