• 网络编程之PC版与Android手机版带断点续传的多线程下载


    一、多线程下载

            多线程下载就是抢占服务器资源
            原理:服务器CPU 分配给每条线程的时间片相同,服务器带宽平均分配给每条线程,所以客户端开启的线程越多,就能抢占到更多的服务器资源。
            
           1、设置开启线程数,发送http请求到下载地址,获取下载文件的总长度
              然后创建一个长度一致的临时文件,避免下载到一半存储空间不够了,并计算每个线程下载多少数据       
           2、计算每个线程下载数据的开始和结束位置
              再次发送请求,用 Range 头请求开始位置和结束位置的数据
           3、将下载到的数据,存放至临时文件中
           4、带断点续传的多线程下载
              定义一个int变量,记录每条线程下载的数据总长度,然后加上该线程的下载开始位置,得到的结果就是下次下载时,该线程的开始位置,把得到的结果存入缓存文件,当文件下载完成,删除临时进度文件。
      1 public class MultiDownload {
      2 
      3     static int ThreadCount = 3;
      4     static int finishedThread = 0;
      5     //确定下载地址
      6     static String filename = "EditPlus.exe";
      7     static String path = "http://192.168.3.45:8080/"+filename;
      8     public static void main(String[] args) {
      9         //1、发送get请求,去获得下载文件的长度
     10         try {
     11             URL url = new URL(path);
     12             HttpURLConnection conn = (HttpURLConnection) url.openConnection();
     13             conn.setRequestMethod("GET");
     14             conn.setConnectTimeout(5000);
     15             conn.setReadTimeout(5000);
     16             
     17             if (conn.getResponseCode()==200) {
     18                 //如果请求成功,拿到所请求资源文件的长度
     19                 int length = conn.getContentLength();
     20                 
     21                 //2、生成一个与原文件同样的大小的临时文件,以免下载一半存储空间不够了
     22                 File file = new File(filename);//演示,所以将保存的文件目录放在工程的同目录
     23                 //使用RandomAccessFile 生成临时文件,可以用指针定位文件的任意位置,
     24                 //而且能够实时写到硬件底层设备,略过缓存,这对下载文件是突然断电等意外是有好处的
     25                 RandomAccessFile  raf = new RandomAccessFile(file, "rwd");//rwd, 实时写到底层设备
     26                 //设置临时文件的大小
     27                 raf.setLength(length);
     28                 raf.close();
     29                 
     30                 //3、计算出每个线程应该下载多少个字节
     31                 int size = length/ThreadCount;//如果有余数,负责最后一部分的线程负责下砸
     32                 
     33                 //开启多线程
     34                 for (int threadId = 0; threadId < ThreadCount; threadId++) {
     35                     //计算每个线程下载的开始位置和结束位置
     36                     int startIndex = threadId*size;  // 开始 = 线程id * size
     37                     int endIndex = (threadId+1)*size - 1; //结束 = (线程id + 1)*size - 1
     38                     //如果是最后一个线程,那么结束位置写死为文件结束位置
     39                     if (threadId == ThreadCount - 1) {
     40                         endIndex = length - 1;
     41                     }
     42                     
     43                     //System.out.println("线程"+threadId+"的下载区间是: "+startIndex+"----"+endIndex);
     44                     new DownloadThread(startIndex,endIndex,threadId).start();
     45                 }
     46             }
     47         } catch (MalformedURLException e) {
     48             e.printStackTrace();
     49         } catch (IOException e) {
     50             e.printStackTrace();
     51         }
     52     }
     53 }
     54 
     55 class DownloadThread extends Thread{
     56     
     57     private int startIndex;
     58     private int endIndex;
     59     private int threadId;
     60 
     61     public DownloadThread(int startIndex, int endIndex, int threadId) {
     62         super();
     63         this.startIndex = startIndex;
     64         this.endIndex = endIndex;
     65         this.threadId = threadId;
     66     }
     67 
     68     @Override
     69     public void run() {
     70          //每个线程再次发送http请求,下载自己对应的那部分数据
     71         try {
     72             File progressFile = new File(threadId+".txt");
     73             //判断进度文件是否存在,如果存在,则接着断点继续下载,如果不存在,则从头下载
     74             if (progressFile.exists()) {
     75                 FileInputStream fis = new FileInputStream(progressFile);
     76                 BufferedReader br = new BufferedReader(new InputStreamReader(fis));
     77                 //从进度文件中度取出上一次下载的总进度,然后与原本的开始进度相加,得到新的开始进度
     78                 startIndex += Integer.parseInt(br.readLine());
     79                 fis.close();
     80             }
     81             System.out.println("线程"+threadId+"的下载区间是:"+startIndex+"----"+endIndex);
     82             
     83             //4、每个线程发送http请求自己的数据
     84             URL url = new URL(MultiDownload.path);
     85             HttpURLConnection conn = (HttpURLConnection) url.openConnection();
     86             conn.setRequestMethod("GET");
     87             conn.setConnectTimeout(5000);
     88             conn.setReadTimeout(5000);
     89             //设置本次http请求所请求的数据的区间
     90             conn.setRequestProperty("Range", "bytes="+startIndex+"-"+endIndex);
     91             
     92             //请求部分数据,响应码是206
     93             if (conn.getResponseCode()==206) {
     94                 //此时,流里只有ThreadCount分之一的原文件数据
     95                 InputStream is = conn.getInputStream();
     96                 byte[] b = new byte[1024];
     97                 int len = 0;
     98                 int total = 0;//total 用于保存断点续传的断点
     99                 //拿到临时文件的输出流
    100                 File file = new File(MultiDownload.filename);
    101                 RandomAccessFile raf = new RandomAccessFile(file, "rwd");
    102                 //把文件的写入位置移动至 startIndex
    103                 raf.seek(startIndex);
    104                 
    105                 while ((len = is.read(b))!=-1) {
    106                     //每次读取流里数据之后,同步把数据写入临时文件
    107                     raf.write(b, 0, len);
    108                     total += len;
    109                     
    110                     //System.out.println("线程" + threadId + "下载了" + total);
    111                     //生成一个一个专门用来记录下载进度的临时文件
    112                     RandomAccessFile progressRaf = new RandomAccessFile(progressFile, "rwd");
    113                     progressRaf.write((total+"").getBytes());
    114                     progressRaf.close();
    115                 }
    116                 System.out.println("线程"+threadId+"下载完了---------------------");
    117                 raf.close();
    118                 
    119                 //当所有的线程下载完之后,将进度文件删除
    120                 MultiDownload.finishedThread++;
    121                 synchronized (MultiDownload.path) {//所有线程使用同一个锁
    122                     if (MultiDownload.finishedThread==MultiDownload.ThreadCount) {
    123                         for (int i = 0; i < MultiDownload.ThreadCount; i++) {
    124                             File f = new File(i+".txt");
    125                             f.delete();
    126                         }
    127                         MultiDownload.finishedThread=0;
    128                     }
    129                 }
    130             }    
    131         } catch (Exception e) {
    132             e.printStackTrace();
    133         }
    134         
    135     }
    136 }
    二、Android手机版带断点续传的多线程下载
         Android手机版的带断点续传的多线程下载逻辑与PC版的几乎一样,只不过在Android手机中耗时操作不能放在主线程,网络下载属于耗时操作,所以多线程下载要在Android中开启一个子线程执行。并使用消息队列机制刷新文本进度条。
    public class MainActivity extends Activity {
        
        static int ThreadCount = 3;
        static int FinishedThread = 0;
        int currentProgess;
        static String Filename = "QQPlayer.exe";
        static String Path = "http://192.168.3.45:8080/"+Filename;
        
        static MainActivity ma;
        static ProgressBar pb;
        static TextView tv;
        static Handler handler = new Handler(){
            public void handleMessage(android.os.Message msg){
                tv.setText((long)pb.getProgress()*100 /pb.getMax()  +"%");
            };
        };
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            
            ma = this;
            pb = (ProgressBar) findViewById(R.id.pb);
            tv = (TextView) findViewById(R.id.tv);
        }
        
        public void download(View v){
            
            Thread t = new Thread(){
                
                @Override
                public void run() {
                    //发送http请求获取文件的长度,创建临时文件
                    try {
                        URL url= new URL(Path);
                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                        conn.setRequestMethod("GET");
                        conn.setConnectTimeout(5000);
                        conn.setReadTimeout(5000);
                        
                        if (conn.getResponseCode()==200) {
                            int length = conn.getContentLength();
                            
                            //设置进度条的最大值就是原文件的总长度
                            pb.setMax(length);
                            
                            //生成一个与原文件相同大小的临时文件
                            File file = new File(Environment.getExternalStorageDirectory(),Filename);
                            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
                            raf.setLength(length);
                            raf.close();
                            
                            //计算每个线程需要下载的数据大小
                            int size = length/ThreadCount;
                            //开启多线程
                            for (int threadId = 0; threadId < ThreadCount; threadId++) {
                                int startIndex = threadId*size;
                                int endIndex = (threadId + 1)*size - 1;
                                if (threadId==ThreadCount - 1) {
                                    endIndex = length - 1;
                                }
                                
                                new DownloadThread(startIndex, endIndex, threadId).start();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            t.start();
        }
        
        class DownloadThread extends Thread{
            private int startIndex;
            private int endIndex;
            private int threadId;
            
            public DownloadThread(int startIndex, int endIndex, int threadId) {
                super();
                this.startIndex = startIndex;
                this.endIndex = endIndex;
                this.threadId = threadId;
            }
            
            @Override
            public void run() {
                // 每个线程发送http请求自己的数据
                try{
                    //先判断是不是断点续传
                    File progessFile = new File(Environment.getExternalStorageDirectory(),threadId+".txt");
                    if (progessFile.exists()) {
                        FileReader fr = new FileReader(progessFile);
                        BufferedReader br = new BufferedReader(fr);
                        int lastProgess = Integer.parseInt(br.readLine());
                        startIndex += lastProgess;
                        
                        //把上次下载的进度显示至进度条
                        currentProgess +=lastProgess;
                        pb.setProgress(currentProgess);
                        //发消息,让主线程刷新文本进度
                        handler.sendEmptyMessage(1);
                        
                        br.close();
                        fr.close();
                    }
                    
                    URL url = new URL(Path);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(5000);
                    conn.setRequestProperty("Range", "bytes="+startIndex+"-"+endIndex);
                    
                    if (conn.getResponseCode()==206) {
                        InputStream is = conn.getInputStream();
                        byte[] buffer = new byte[1024];
                        int len = 0;
                        int total = 0;
                        
                        File file = new File(Environment.getExternalStorageDirectory(),Filename);
                        RandomAccessFile raf = new RandomAccessFile(file, "rwd");
                        raf.seek(startIndex);
                        
                        while ((len = is.read(buffer))!= -1) {
                            raf.write(buffer, 0, len);
                            total += len;
                            
                            //每次读取流里数据之后,把本次读取的数据的长度显示至进度条
                            currentProgess += len;
                            pb.setProgress(currentProgess);
                            //发消息,让主线程刷新文本进度
                            handler.sendEmptyMessage(1);
                            //生成临时文件保存下载进度,用于断点续传,在所有线程现在完毕后删除临时文件
                            RandomAccessFile progressRaf = new RandomAccessFile(progessFile, "rwd");
                            progressRaf.write((total+"").getBytes());
                            progressRaf.close();
                        }
                        raf.close();
                        System.out.println("线程"+threadId+"下载完了");
                        
                        //当所有线程都下在完了之后,删除临时进度文件
                        FinishedThread++;
                        synchronized (Path) {
                            if (FinishedThread==ThreadCount) {
                                for (int i = 0; i < ThreadCount; i++) {
                                    File f = new File(Environment.getExternalStorageDirectory(),i+".txt");
                                    f.delete();
                                }
                                FinishedThread=0;
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }





  • 相关阅读:
    #网络流,最小割#洛谷 1344 [USACO4.4]追查坏牛奶Pollutant Control
    #线段树,倒序#CF356A Knight Tournament
    #错排,高精度#洛谷 3182 [HAOI2016]放棋子
    #KMP,dp#洛谷 3426 [POI2005]SZA-Template
    #差分约束系统,Spfa,SLF优化#Hdu 3666 THE MATRIX PROBLEM
    #min_max容斥#Hdu 4336 Card Collector
    #组合计数,卢卡斯定理#D 三元组
    #计数,记忆化搜索#C 连边方案
    #区间dp,离散#D 弱者对决
    #dp#C 公共子序列
  • 原文地址:https://www.cnblogs.com/rocomp/p/4863395.html
Copyright © 2020-2023  润新知