基于Netty构建HTTP访问分为两类,使用浏览器访问的和使用Netty客户端访问。在介绍之前,先简单说一下如何使用Netty实现Http服务的。
Netty的Http服务的流程是:
1、Client向Server发送http请求。
2、Server端对http请求进行解析。
3、Server端向client发送http响应。
4、Client对http响应进行解析。
在网上看到一个很好的流程图,很能说明问题:
netty 实现http服务器
1.HttpFileServer.java
import com.ghq.netty.common.CommonUtil;
import com.ghq.netty.common.ServerUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
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;
import io.netty.handler.stream.ChunkedWriteHandler;
/**
* @author ${user}
* @Description:
* @Date: Created in 15:38 2018/7/2
* @Modified By:
*/
public class HttpFileServer {
private static final String DEFAULT_URL = "/src";
/*public void run(final int port,final String url) throws Exception{
ServerUtil.bind(port, new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast("http-decoder",new HttpRequestDecoder());
*//**
* httpObject 解码器,
* 它的作用是将多个消息转换为单一的FullHttpRequest或FullHttpResponse
* 对象,原因是HTTP 解码器在每个HTTP消息中会生成多个消息对象 (
* HttpRequest/HttpResponse
* ,HttpContent,LastHttpContent)
*//*
ch.pipeline().addLast("http-aggregator",new HttpObjectAggregator(65536));
*//**
* HTTP 响应消息编码器
*//*
ch.pipeline().addLast("http-encoder",new HttpResponseEncoder());
*//**
* ChunkedWriteHandler
* 的主要作用是支持异步发送大的码流(例如大文件传输),但不占用过多的内存,防止JAVA内存溢出
*//*
ch.pipeline().addLast("http-chunked",new ChunkedWriteHandler());
//业务处理类
ch.pipeline().addLast("fileServerHandler",new ABF(url));
}
});
}
public static void main(String[] args) throws Exception {
int port = CommonUtil.getPort(args);
String url = DEFAULT_URL;
new HttpFileServer().run(port,url);
}*/
public void run(final int port, final String url) throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch)
throws Exception {
// http 请求消息解码器,
ch.pipeline().addLast("http-decoder",
new HttpRequestDecoder());
/**
* httpObject 解码器,
* 它的作用是将多个消息转换为单一的FullHttpRequest或FullHttpResponse
* 对象,原因是HTTP 解码器在每个HTTP消息中会生成多个消息对象 (
* HttpRequest/HttpResponse
* ,HttpContent,LastHttpContent)
*/
ch.pipeline().addLast("http-aggregator",
new HttpObjectAggregator(65536));
/*
* HTTP 响应消息编码器
*/
ch.pipeline().addLast("http-encoder",
new HttpResponseEncoder());
/*
* ChunkedWriteHandler
* 的主要作用是支持异步发送大的码流(例如大文件传输),但不占用过多的内存,防止JAVA内存溢出
*/
ch.pipeline().addLast("http-chunked",
new ChunkedWriteHandler());
/*
* 业务处理类
*/
ch.pipeline().addLast("fileServerHandler",
new HttpFileServerHandler(url));
}
});
ChannelFuture future = b.bind("127.0.0.1", port).sync();
System.out.println("HTTP文件目录服务器启动,网址是 : " + "http://localhost:"
+ port + url);
future.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
int port = 9191;
if (args.length > 0) {
try {
port = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
String url = DEFAULT_URL;
if (args.length > 1){
url = args[1];
}
new HttpFileServer().run(port, url);
}
}
2.HttpFileServerHandler.java
package com.ghq.netty.chp10;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.http.*;
import io.netty.handler.stream.ChunkedFile;
import io.netty.util.CharsetUtil;
import javax.activation.MimetypesFileTypeMap;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.regex.Pattern;
/**
* @author ${user}
* @Description:
* @Date: Created in 15:46 2018/7/2
* @Modified By:
*/
public class HttpFileServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
@Override
protected void messageReceived(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
if(!request.getDecoderResult().isSuccess()){
sendError(ctx,HttpResponseStatus.BAD_REQUEST);
return;
}
if(request.getMethod() != HttpMethod.GET){
sendError(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED);
return;
}
final String uri = request.getUri();
final String path = sanitizeUri(uri);
if(path == null){
sendError(ctx, HttpResponseStatus.FORBIDDEN);
return;
}
File file = new File(path);
if(file.isHidden() || !file.exists()){
sendError(ctx, HttpResponseStatus.NOT_FOUND);
return;
}
RandomAccessFile randomAccessFile = null;
try {
// 以只读的方式打开文件
randomAccessFile = new RandomAccessFile(file, "r");
} catch (FileNotFoundException fnfe) {
sendError(ctx, HttpResponseStatus.NOT_FOUND);
return;
}
long fileLength = randomAccessFile.length();
HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
HttpHeaders.setContentLength(response, fileLength);
setContentTypeHeader(response, file);
if (HttpHeaders.isKeepAlive(request)) {
response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
}
ctx.write(response);
ChannelFuture sendFileFuture;
sendFileFuture = ctx.write(new ChunkedFile(randomAccessFile, 0,
fileLength, 8192), ctx.newProgressivePromise());
sendFileFuture.addListener(new ChannelProgressiveFutureListener() {
@Override
public void operationProgressed(ChannelProgressiveFuture future,
long progress, long total) {
// total unknown
if (total < 0) {
System.err.println("Transfer progress: " + progress);
} else {
System.err.println("Transfer progress: " + progress + " / "
+ total);
}
}
@Override
public void operationComplete(ChannelProgressiveFuture future)
throws Exception {
System.out.println("Transfer complete.");
}
});
/*
* 如果是chunked 编码, 最后需要发送一个编码结束的空消息体,将LastHttpContent的EMPTY_LAST_CONTENT
* 发送到缓存区中,标识所有的消息体已经发送完成,同时调用flush方法将之前在发送缓冲区的消息刷新到SocketChannel中发送给对方
*/
ChannelFuture lastContentFuture = ctx
.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
/*
* 如果是非 Keep-Alive 的,最后一包消息发送完之后,服务端要主动关闭连接.
*/
if (!HttpHeaders.isKeepAlive(request)) {
lastContentFuture.addListener(ChannelFutureListener.CLOSE);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
cause.printStackTrace();
if (ctx.channel().isActive()) {
sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR);
}
}
private String sanitizeUri(String uri) {
try {
uri = URLDecoder.decode(uri,CharsetUtil.UTF_8.name());
}catch (UnsupportedEncodingException e){
e.printStackTrace();
try {
uri = URLDecoder.decode(uri,CharsetUtil.ISO_8859_1.name());
} catch (UnsupportedEncodingException e1) {
throw new Error();
}
}
//
uri = uri.replace("/", File.separator);
if(uri.contains(File.separator+".")
|| uri.contains("."+File.separator) || uri.startsWith(".")
|| uri.endsWith(".") || INSECURE_URI.matcher(uri).matches()){
return null;
}
return System.getProperty("user.dir")+ File.separator+uri;
}
private static final Pattern ALLOWED_FILE_NAME = Pattern.compile("[A-Za-z0-9][-_A-Za-z0-9\\.]*");
private static final Pattern INSECURE_URI = Pattern.compile(".*[<>&\"].*");
private static void sendRedirect(ChannelHandlerContext ctx, String newUri) {
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FOUND);
response.headers().set(HttpHeaders.Names.LOCATION, newUri);
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}
private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, Unpooled.copiedBuffer("Failure: "
+ status + "\r\n", CharsetUtil.UTF_8));
response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=UTF-8");
// Close the connection as soon as the error message is sent.
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}
private static void setContentTypeHeader(HttpResponse response, File file) {
MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
response.headers().set(HttpHeaders.Names.CONTENT_TYPE,
mimeTypesMap.getContentType(file.getPath()));
}
private static void sendListing(ChannelHandlerContext ctx, File dir) {
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/html; charset=UTF-8");
StringBuilder buf = new StringBuilder();
String dirPath = dir.getPath();
buf.append("<!DOCTYPE html>\r\n");
buf.append("<html><head><title>");
buf.append(dirPath);
buf.append(" 目录:");
buf.append("</title></head><body>\r\n");
buf.append("<h3>");
buf.append(dirPath).append(" 目录:");
buf.append("</h3>\r\n");
buf.append("<ul>");
buf.append("<li>链接:<a href=\"../\">..</a></li>\r\n");
for (File f : dir.listFiles()) {
if (f.isHidden() || !f.canRead()) {
continue;
}
String name = f.getName();
if (!ALLOWED_FILE_NAME.matcher(name).matches()) {
continue;
}
buf.append("<li>链接:<a href=\"");
buf.append(name);
buf.append("\">");
buf.append(name);
buf.append("</a></li>\r\n");
}
buf.append("</ul></body></html>\r\n");
ByteBuf buffer = Unpooled.copiedBuffer(buf, CharsetUtil.UTF_8);
response.content().writeBytes(buffer);
buffer.release();
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}
}
测试结果:启动服务器,控制台信息:
HTTP文件目录服务器启动,网址是 : http://localhost:9191/src
打开浏览器访问:http://localhost:9191/src
结果如下: