<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.68.Final</version>
</dependency>
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
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.*;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedFile;
import io.netty.handler.stream.ChunkedWriteHandler;
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.InetSocketAddress;
import java.net.URLDecoder;
import java.util.regex.Pattern;
public class HttpFileServer {
private static final String DEFAULT_URL = "";
public static void main(String...args) throws InterruptedException {
int port = 8080;
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];
}
final String URL = url;
EventLoopGroup parentGroup = new NioEventLoopGroup();
EventLoopGroup childGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(parentGroup, childGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.localAddress(new InetSocketAddress(port))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
// 请求消息解码器
pipeline.addLast("http-decoder", new HttpRequestDecoder());
// 目的是将多个消息转换为单一的FullHttpRequest或者FullHttpResponse对象
pipeline.addLast("http-aggregator", new HttpObjectAggregator(65535));
// 响应解码器
pipeline.addLast("http-encoder", new HttpResponseEncoder());
//目的是支持异步大的码流传输,但不占用过多的内存
pipeline.addLast("http-chunked", new ChunkedWriteHandler());
pipeline.addLast("fileServerHandler", new HttpFileServerHandler(URL));
}
});
ChannelFuture f = b.bind().sync();
System.out.println("HTTP文件目录服务器启动,网址是 : " + "http://127.0.0.1:" + port);
f.channel().closeFuture().sync();
}finally {
parentGroup.shutdownGracefully().sync();
childGroup.shutdownGracefully().sync();
}
}
private static class HttpFileServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
private static final Pattern INSECURE_URI = Pattern.compile(".*[<>&\"].*");
private static final Pattern ALLOWED_FILE_NAME = Pattern.compile("[A-Za-z0-9][-_A-Za-z0-9\\.]*");
private final String url;
public HttpFileServerHandler(String url) {
this.url = url;
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
// 解码失败
if (!request.decoderResult().isSuccess()){
// 400错误
sendError(ctx, HttpResponseStatus.BAD_REQUEST);
return;
}
// 不是GET请求
if (request.method()!=HttpMethod.GET){
// 405错误
sendError(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED);
}
final String uri = request.uri();
final String path = sanitizeUri(this.url + uri);
// 文件校验失败
if (path==null){
// 403
sendError(ctx, HttpResponseStatus.FORBIDDEN);
return;
}
File file = new File(path);
if (file.isHidden() || !file.exists()){
// 404
sendError(ctx, HttpResponseStatus.NOT_FOUND);
return;
}
// 文件是目录,发送文件的连接给客户端
if (file.isDirectory()){
if (uri.endsWith("/")){
sendListing(ctx, file);
} else {
sendRedirect(ctx, uri + '/');
}
return;
}
if (!file.isFile()) {
// 403
sendError(ctx, HttpResponseStatus.FORBIDDEN);
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);
HttpUtil.setContentLength(response, fileLength);
// java文件直接在线打开
if (file.getName().endsWith(".java")){
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
}else {
MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
String contentType = mimeTypesMap.getContentType(file.getPath());
if (HttpHeaderValues.TEXT_PLAIN.toString().equals(contentType)){
contentType += "; charset=UTF-8";
}
response.headers().set(HttpHeaderNames.CONTENT_TYPE, contentType);
}
if (HttpUtil.isKeepAlive(request)){
response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
}
ctx.write(response);
// 将文件写入到发送缓冲区
ChannelFuture 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) {
if (total < 0) { // total unknown
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.");
}
});
// 最后发送一个编码结束的空消息体
ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
if (!HttpUtil.isKeepAlive(request)){
lastContentFuture.addListener(ChannelFutureListener.CLOSE);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
if (ctx.channel().isActive()) {
// 500
sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR);
}
}
private void sendRedirect(ChannelHandlerContext ctx, String s) {
// 302重定向
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FOUND);
response.headers().set(HttpHeaderNames.LOCATION, s);
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}
private void sendListing(ChannelHandlerContext ctx, File dir) {
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
StringBuffer buf = new StringBuffer();
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");
final File[] files = dir.listFiles();
for (File file : files) {
if (file.isHidden()||!file.canRead()){
continue;
}
String name = file.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);
}
private String sanitizeUri(String uri) {
try {
uri = URLDecoder.decode(uri, "UTF-8");
} catch (UnsupportedEncodingException e) {
try {
uri = URLDecoder.decode(uri, "ISO-8859-1");
} 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") + uri;
}
private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
FullHttpResponse response = new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1,
status,
Unpooled.copiedBuffer("Failure: " + status.toString(), CharsetUtil.UTF_8));
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}
}
}