Netty是一个NIO框架,让你快速、简单的的开发网络应用。它是一种新的开发网络应用的方式,使得开发网络应用更加简单,容易扩展。它隐藏了许多复杂的细节,并提供简单的api让你的业务逻辑和网络处理代码分离开来。Netty的所有api都是异步的,如果大家不了解异步IO,可以先学习一下异步IO方面的知识。
本文主要是写一个入门程序让大家了解netty的强大。本文主要编写一个基于http协议的文件服务器,可以使用浏览器来访问服务器的目录,下载文件等。如果不熟悉http协议可以先了解http相应相关的内容。
本入门程序只有两个java文件,开发环境为jdk1.7,依赖netty-all-5.0.0.Alpha2.jar
HttpFileServer.java
package test.http;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
public class HttpFileServer {
private final int port=80;
private final String localDir="d:/";
public void run() throws Exception{
EventLoopGroup acceptorGroup = new NioEventLoopGroup();
EventLoopGroup clientGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBookstrap = new ServerBootstrap();
serverBookstrap.group(acceptorGroup, clientGroup).channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 100)
.childHandler(new ChannelInitializer<SocketChannel>(){
protected void initChannel(SocketChannel sc) throws Exception {
sc.pipeline().addLast("http-decoder",new HttpRequestDecoder());
sc.pipeline().addLast("http-aggregator",new HttpObjectAggregator(64*1024));
sc.pipeline().addLast("http-encoder",new HttpResponseEncoder());
sc.pipeline().addLast("http-handler",new HttpRequestHandler(localDir));
}
});
ChannelFuture channelFuture = serverBookstrap.bind(port).sync();
channelFuture.channel().closeFuture().sync();
} finally {
acceptorGroup.shutdownGracefully();
clientGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
new HttpFileServer().run();
}
}
Netty提类似linux管道机制的使用方法,可以向pipeline添加多个ChannelHandler,Netty会依次调用添加的handler来处理,这个很像java web中的servlet