1. 程式人生 > >06-netty之http之檔案伺服器

06-netty之http之檔案伺服器

Netty是一個NIO框架,讓你快速、簡單的的開發網路應用。它是一種新的開發網路應用的方式,使得開發網路應用更加簡單,容易擴充套件。它隱藏了許多複雜的細節,並提供簡單的api讓你的業務邏輯和網路處理程式碼分離開來。Netty的所有api都是非同步的,如果大家不瞭解非同步IO,可以先學習一下非同步IO方面的知識。

package netty.http;

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 lilinfeng * @date 2014年2月14日 * @version 1.0 */ public class HttpFileServer { // 這裡目錄要寫完整的相對路徑,包括main/java private static final String DEFAULT_URL = "/src/main/java/netty"; 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 { ch.pipeline().addLast("http-decoder", new HttpRequestDecoder()); ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536)); // 新增HTTP響應編碼器,對HTTP響應訊息進行編碼 ch.pipeline().addLast("http-encoder", new HttpResponseEncoder()); // 新增Chunked handler,主要作用是支援非同步傳送大的碼流(例如大檔案傳輸) // 但是不佔用過多的記憶體,防止發生java記憶體溢位錯誤 ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler()); // HttpFileServerHandler用於檔案伺服器的業務邏輯處理 ch.pipeline().addLast("fileServerHandler", new HttpFileServerHandler(url)); } }); String host = "127.0.0.1"; ChannelFuture future = b.bind(host, port).sync(); System.out.println("HTTP檔案目錄伺服器啟動,網址是 : http://" + host +":" + port + url); future.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } public static void main(String[] args) throws Exception { int port = 8081; 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); } }
package netty.http;

import static io.netty.handler.codec.http.HttpHeaders.isKeepAlive;
import static io.netty.handler.codec.http.HttpHeaders.setContentLength;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONNECTION;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpHeaders.Names.LOCATION;
import static io.netty.handler.codec.http.HttpMethod.GET;
import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN;
import static io.netty.handler.codec.http.HttpResponseStatus.FOUND;
import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR;
import static io.netty.handler.codec.http.HttpResponseStatus.METHOD_NOT_ALLOWED;
import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelProgressiveFuture;
import io.netty.channel.ChannelProgressiveFutureListener;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.handler.stream.ChunkedFile;
import io.netty.util.CharsetUtil;

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;

import javax.activation.MimetypesFileTypeMap;

/**
 * @author lilinfeng
 * @date 2014年2月14日
 * @version 1.0
 */
public class HttpFileServerHandler extends
    SimpleChannelInboundHandler<FullHttpRequest> {
    private final String url;

    public HttpFileServerHandler(String url) {
        this.url = url;
    }

    /**
     *   DefaultFullHttpRequest, decodeResult: success)
     *   GET /src/main/java/netty/ HTTP/1.1
     *   Host: 127.0.0.1:8081
     *   Connection: keep-alive
     *   Cache-Control: max-age=0
     *   User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36
     *   Upgrade-Insecure-Requests: 1
     *   Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*;q=0.8
     *   Accept-Encoding: gzip, deflate, br
     *   Accept-Language: zh-CN,zh;q=0.9
     *   Content-Length: 0
     *
     *
     *   DefaultFullHttpRequest, decodeResult: success)
     *   GET /favicon.ico HTTP/1.1
     *   Host: 127.0.0.1:8081
     *   Connection: keep-alive
     *   Pragma: no-cache
     *   Cache-Control: no-cache
     *   User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36
     *   Accept: image/webp,image/*,*;q=0.8
     *   Referer: http://127.0.0.1:8081/src/main/java/netty/
     *   Accept-Encoding: gzip, deflate, sdch, br
     *   Accept-Language: zh-CN,zh;q=0.8
     *   Content-Length: 0
     *
     *   這裡發現,每次重新整理,或者點選都會有兩個請求,很鬱悶?
     *   瀏覽器每次發起請求,都會同時請求一次favicon.ico(本次不討論瀏覽器快取了favicon.ico)
     *
    */
    @Override
    public void messageReceived(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {

        // 過濾掉瀏覽器每次發起請求,都會同時請求一次favicon.ico
        if(request.getUri().equals("/favicon.ico")){
            return;
        }

        System.out.println("伺服器接受訊息"+request);

        // 首先對HTTP請求小弟的解碼結果進行判斷,如果解碼失敗,直接構造HTTP 400錯誤返回。
        if (!request.getDecoderResult().isSuccess()) {
            sendError(ctx, BAD_REQUEST);
            return;
        }
        // 請求方法:如果不是從瀏覽器或者表單設定為get請求,構造http 405錯誤返回
        if (request.getMethod() != GET) {
            sendError(ctx, METHOD_NOT_ALLOWED);
            return;
        }
        // 對請求的的URL進行包裝
        final String uri = request.getUri();
        // 展開URL分析
        final String path = sanitizeUri(uri);


        if (path == null) {
            sendError(ctx, FORBIDDEN);
            return;
        }
        File file = new File(path);
        // 如果檔案不存在或者是系統隱藏檔案,則構造404 異常返回
        if (file.isHidden() || !file.exists()) {
            sendError(ctx, NOT_FOUND);
            return;
        }
        // 如果檔案是目錄,則傳送目錄的連線給客戶端瀏覽器
        if (file.isDirectory()) {
            if (uri.endsWith("/")) {
                sendListing(ctx, file);
            } else {
                sendRedirect(ctx, uri + '/');
            }
            return;
        }
        // 使用者在瀏覽器上第幾超連結直接開啟或者下載檔案,合法性監測
        if (!file.isFile()) {
            sendError(ctx, FORBIDDEN);
            return;
        }

        // IE下才會開啟檔案,其他瀏覽器都是直接下載
        // 隨機檔案讀寫類以讀的方式開啟檔案
        RandomAccessFile randomAccessFile = null;
        try {
            randomAccessFile = new RandomAccessFile(file, "r");// 以只讀的方式開啟檔案
        } catch (FileNotFoundException fnfe) {
            sendError(ctx, NOT_FOUND);
            return;
        }
        // 獲取檔案長度,構建成功的http應答訊息
        long fileLength = randomAccessFile.length();
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
        setContentLength(response, fileLength);
        setContentTypeHeader(response, file);
        if (isKeepAlive(request)) {
            response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
        }
        ctx.write(response);


        ChannelFuture sendFileFuture;
        // 同過netty的村可多File物件直接將檔案寫入到傳送緩衝區,最後為sendFileFeature增加GenericFeatureListener,
        // 如果傳送完成,列印“Transfer complete”
        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 (!isKeepAlive(request)) {
            lastContentFuture.addListener(ChannelFutureListener.CLOSE);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
        throws Exception {
    cause.printStackTrace();
    if (ctx.channel().isActive()) {
        sendError(ctx, INTERNAL_SERVER_ERROR);
    }
    }

    private static final Pattern INSECURE_URI = Pattern.compile(".*[<>&\"].*");

    private String sanitizeUri(String uri) {


        try {
            // 使用JDK的URLDecoder進行解碼
            uri = URLDecoder.decode(uri, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            try {
            uri = URLDecoder.decode(uri, "ISO-8859-1");
            } catch (UnsupportedEncodingException e1) {
            throw new Error();
            }
        }
        // URL合法性判斷
        if (!uri.startsWith(url)) {
            return null;
        }
        if (!uri.startsWith("/")) {
            return null;
        }
        // 將硬編碼的檔案路徑
        uri = uri.replace('/', File.separatorChar);
        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\\.]*");

    /**
     * 這裡是構建了一個html頁面返回給瀏覽器
     * @param ctx
     * @param dir
     */
    private static void sendListing(ChannelHandlerContext ctx, File dir) {
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK);
        response.headers().set(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);
    }

    private static void sendRedirect(ChannelHandlerContext ctx, String newUri) {
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, FOUND);
        response.headers().set(LOCATION, newUri);
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

    private static void sendError(ChannelHandlerContext ctx,
        HttpResponseStatus status) {

        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1,
            status, Unpooled.copiedBuffer("Failure: " + status.toString()
                + "\r\n", CharsetUtil.UTF_8));
        response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

    private static void setContentTypeHeader(HttpResponse response, File file) {

        MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
        response.headers().set(CONTENT_TYPE,
            mimeTypesMap.getContentType(file.getPath()));
    }
}

這裡寫圖片描述