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(); } }