Netty—Http服务器
一.简介
Netty一个高性能IO工具包,主要用于开发HTTP服务器,HTTPS服务器,WebSocket服务器,TCP服务器,UDP服务器和在JVM管道。用Netty开发的服务器可单独运行(即:在main()函数里调用),不需要部署在类似tomcat的容器里。Netty使用单线程并发模型,并围绕非阻塞NIO设计,所以性能较高。
二.http服务器示例
public class NerryHttpServer {
public static void main(String[] args) {
EventLoopGroup group = new NioEventLoopGroup();
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(group);
bootstrap.channel(NioServerSocketChannel.class);
bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast("http-decoder", new HttpRequestDecoder());
socketChannel.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65535));// 将多个消息转化成一个
socketChannel.pipeline().addLast("http-encoder", new HttpResponseEncoder());
socketChannel.pipeline().addLast("http-chunked", new ChunkedWriteHandler());// 解决大码流的问题
socketChannel.pipeline().addLast(new NettyServerHandler());
}
});
try {
ChannelFuture channelFuture = bootstrap.bind(8899).sync();
channelFuture.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
group.shutdownGracefully();
}
}
}
class NettyServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
try {
String requestMethod = "";
if (msg.getMethod() == HttpMethod.GET) {
requestMethod = "the request method is GET";
} else if (msg.getMethod() == HttpMethod.POST) {
requestMethod = "the request method is POST";
}
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
ByteBuf responseBuf = Unpooled.copiedBuffer(requestMethod, CharsetUtil.UTF_8);
response.content().writeBytes(responseBuf);
responseBuf.release();
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
} catch (Exception e) {
e.printStackTrace();
}
}
}