netty入門(一)
Netty是一個高性能 事件驅動的異步的非堵塞的IO(NIO)框架,用于建立TCP等底層的連接,基于Netty可以建立高性能的Http服務器。
1、首先來復習下非堵塞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中。
網絡編程NIO中還有一個核心對象Selector,它可以注冊到很多個Channel上,監聽各個Channel上發生的事件,并且能夠根據事件情況決定Channel讀寫。這樣,通過一個線程管理多個Channel,就可以處理大量網絡連接了。
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 上的這個注冊。
2、異步
CallBack:回調是異步處理經常用到的編程模式,回調函數通常被綁定到一個方法上,并且在方法完成之后才執行,這種處理方式在javascript當中得到了充分的運用。回調給我們帶來的難題是當一個問題處理過程中涉及很多回調時,代碼是很難讀的。
Futures:Futures是一種抽象,它代表一個事情的執行過程中的一些關鍵點,我們通過Future就可以知道任務的執行情況,比如當任務沒完成時我們可以做一些其它事情。它給我們帶來的難題是我們需要去判斷future的值來確定任務的執行狀態。
3、netty到底怎么工作的呢?
直接來看個最簡單的實例
服務器端
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來處理每一個鏈接請求
- 所有準備好之后調用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();
}
}