实现http 服务器的断点下载功能

2019-11-29  本文已影响0人  贼噶人
package com.jove.smarthttp;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;

import org.smartboot.http.HttpBootstrap;
import org.smartboot.http.HttpRequest;
import org.smartboot.http.HttpResponse;
import org.smartboot.http.enums.HttpStatus;
import org.smartboot.http.server.handle.HttpHandle;
import org.smartboot.http.utils.StringUtils;

/**
 * Hello world!
 *
 */
public class App {
    static long BUFFER_SIZE = 1024 * 1024;
    public static void main(String[] args) {
        HttpBootstrap bootstrap = new HttpBootstrap();
        bootstrap.pipeline().next(new HttpHandle() {
            @SuppressWarnings("resource")
            @Override
            public void doHandle(HttpRequest request, HttpResponse response) throws IOException {
                if (request.getRequestURI().endsWith(".mp4")) {
                    long begin = 0;
                    long end = 0;
                    try {
                        if (request.getHeaders().containsKey("Range") 
                                || request.getHeaders().containsKey("range")) {
                            String range = StringUtils.isEmpty(range = request.getHeaders().get("Range"))
                                    ? request.getHeaders().get("range"): range;
                            final String[] rangeBytes = range.split("=")[1].split("-");
                            if (rangeBytes.length == 1) {
                                begin = Integer.parseInt(rangeBytes[0]);
                            } else if (rangeBytes.length == 2) {
                                begin = Integer.parseInt(rangeBytes[0]);
                                end = Integer.parseInt(rangeBytes[1]);
                            }
                        }
                    } catch (Exception e) {

                    }
                    FileChannel channel = null;
                    try {
                        channel = new FileInputStream("C:\\Users\\63590\\Desktop\\wk_detail.mp4")
                                .getChannel();
                        response.setHeader("Accept-Range", "bytes");
                        response.setContentType("video/mp4");
                        long position = Math.max(begin, 0);
                        end = channel.size();
                        if(begin > 0 && begin < channel.size()) {
                            response.setHttpStatus(HttpStatus.PARTIAL_CONTENT);
                            response.setContentLength((int)(channel.size() - begin));
                            response.setHeader("Content-Range", "bytes "+begin+"-"+channel.size());
                        } else {
                            response.setHttpStatus(HttpStatus.OK);
                            response.setContentLength((int)channel.size()) ;
                        }
                        final byte[] dataFull = new byte[(int)BUFFER_SIZE];
                        while(position < end) {
                            final MappedByteBuffer mappedByteBuffer = channel.map(MapMode.READ_ONLY
                                    , position, Math.min(BUFFER_SIZE, end - position));
                            final int remaining = mappedByteBuffer.remaining();
                            position += remaining;
                            if(remaining == BUFFER_SIZE) {
                                mappedByteBuffer.get(dataFull);
                                response.write(dataFull);
                            }
                            else {
                                final byte[] data = new byte[remaining];
                                mappedByteBuffer.get(data);
                                response.write(data);
                            }
                        }
                    } catch (Exception e) {
                        
                    }finally {
                        if(null != channel) {
                            channel.close();
                        }
                    }
                }
            }
        });
        bootstrap.setPort(8080).start();
    }
}

上一篇下一篇

猜你喜欢

热点阅读