首页>代码>java socket多线程网络传输多个文件,支持断点续传>/FileTransfer/src/com/my/file/transfer/test/TransferClient1.java
package com.my.file.transfer.test;

import java.io.BufferedInputStream;  
import java.io.DataInputStream;  
import java.io.DataOutputStream;  
import java.io.File;  
import java.io.FileInputStream;
import java.io.RandomAccessFile;
import java.net.Socket;  
import java.util.ArrayList;
import java.util.Random;  
import java.util.Vector;  
import java.util.concurrent.ExecutorService;  
import java.util.concurrent.Executors;
  
public class TransferClient1 {
	//socket 多线程网络传输多个文件

	private static ArrayList<String> fileList = new ArrayList<String>();
    
    private String sendFilePath = Constants.SEND_FILE_PATH;
    
    //
    private final String serverPath = Constants.SERVER_FILE_PATH;
    
    /** 
     * 带参数的构造器,用户设定需要传送文件的文件夹 
     * @param filePath 
     */
    public TransferClient1(String filePath){
        getFilePath(filePath);
    }
    
    /** 
     * 不带参数的构造器。使用默认的传送文件的文件夹 
     */
    public TransferClient1(){  
        getFilePath(sendFilePath);  
    }  
      
    public void service(){
        ExecutorService executorService = Executors.newCachedThreadPool();
        Vector<Integer> vector = getRandom(fileList.size());
        for(Integer integer : vector){
            String filePath = fileList.get(integer.intValue());
            executorService.execute(sendFile(filePath));
        }
    }
  
    private void getFilePath(String dirPath){
        File dir = new File(dirPath);
        File[] files = dir.listFiles();
        if(files == null){
            return;
        }
        for(int i = 0; i < files.length; i++){
            if(files[i].isDirectory()){
                getFilePath(files[i].getAbsolutePath());
            }
            else {
                fileList.add(files[i].getAbsolutePath());
            }
        }
    }
      
    private Vector<Integer> getRandom(int size){
        Vector<Integer> v = new Vector<Integer>();
        Random r = new Random();
        boolean b = true;
        while(b){
            int i = r.nextInt(size);
            if(!v.contains(i))
                v.add(i);
            if(v.size() == size)
                b = false;
        }
        return v;
    }
    
    private static Runnable sendFile(final String filePath){
        return new Runnable(){
            
            private Socket socket = null;
            private String ip ="127.0.0.1";
            private int port = 10000;
            public void run() {
                System.out.println("开始发送文件:" + filePath);
                File file = new File(filePath);
                
                if(createConnection()){
                    int bufferSize = 8192;
                    byte[] buf = new byte[bufferSize];
                    try {
                        DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath)));
                        // 创建一个新的数据输出流,将数据写入指定基础输出流
                        DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
                        
                        DataInputStream dis = new DataInputStream(socket.getInputStream());
                        
                        dos.writeUTF(file.getName());
                        //清空此数据输出流
                        dos.flush();
                        dos.writeLong(file.length());
                        dos.flush();
                        
                        String marklength= dis.readUTF();
                        if("noexsits".equals(marklength)){
                        	System.out.println("文件["+file.getName()+"]直接传输!");
                        	int num = 0;
                        	long numlth =0;
                        	while((num=fis.read(buf))!=-1){
                        		dos.write(buf,0,num);
                        		dos.flush();
                        		numlth+=num;
                        		System.out.println("文件["+file.getName()+"]已传送"+numlth*100L/file.length()+"%");
                        	}
                        	dos.flush();
                        	this.socket.shutdownOutput();
                        	String record = dis.readUTF();
                        	System.out.println("文件["+file.getName()+"]传输结束1:"+record);
                        }else{
                        	System.out.println("读取服务器端["+file.getName()+"]文件长度!");
                        	long serlth = Long.parseLong(marklength);
                        	RandomAccessFile raf = new RandomAccessFile(filePath,"r");
                        	raf.seek(serlth);//设置到此文件开头测量到的文件指针偏移量,在该位置发生下一个读取或写入操作。
//                        	raf.skipBytes((int) serlth);// 参数可以为负数,当为负数时,则该方法不起作用
                        	//FileInputStream fiss = new FileInputStream(filePath);
                        	//fiss.skip(serlth);
                        	int serstart =0;
                        	
                        	while((serstart=raf.read(buf))!=-1){
                        		dos.write(buf,0,serstart);
                        		dos.flush();
                        		serlth+=serstart;
                        		System.out.println("文件["+file.getName()+"]已传送"+serlth*100L/file.length()+"%");
                        	}
                        	dos.flush();
                        	raf.close();
                        	this.socket.shutdownOutput();
                        	String record = dis.readUTF();
                        	System.out.println("文件["+file.getName()+"]传输结束2:"+record);
                        }
                       
                       fis.close();
                       dos.close();
                       dis.close();
                       socket.close();
                       System.out.println("文件 " + filePath + "传输完成!");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            
            private boolean createConnection() {
                try {
                    socket = new Socket(ip, port);
                    System.out.println("连接服务器成功!");
                    return true;
                } catch (Exception e) {
                    System.out.println("连接服务器失败!");
                    return false;
                }
            }
           
        };
    }
    
    public static void main(String[] args){
        new TransferClient1().service();
    }
}
最近下载更多
skiler  LV4 2023年9月23日
lironggang  LV38 2022年12月22日
linboss  LV4 2022年8月18日
里更debug  LV10 2022年5月10日
yuxinnan  LV4 2022年2月23日
青春玩命的年代  LV2 2021年12月30日
微量的记忆  LV10 2021年4月12日
李海洋  LV12 2020年11月10日
menmenge  LV1 2020年6月24日
lyd19931203  LV21 2020年6月12日
最近浏览更多
851690469  LV1 2023年10月18日
skiler  LV4 2023年9月23日
lifei  LV3 2023年3月12日
takefu 2022年12月6日
暂无贡献等级
luojian5301314 2022年8月19日
暂无贡献等级
linboss  LV4 2022年8月18日
MoonSight  LV1 2022年7月1日
陈小灏  LV14 2022年5月23日
bearloadprogress  LV7 2022年5月12日
里更debug  LV10 2022年5月10日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友