java socket传输文件及文件夹数据

服务器端:

package test;  
  
import java.io.File;  
import java.io.FileOutputStream;  
import java.io.InputStream;  
import java.io.OutputStream;  
import java.io.PrintStream;  
import java.net.ServerSocket;
import java.net.Socket;  
  
public class TCPServer {  
    public static void main(String[] args) throws Exception{  
        //System.setOut(new PrintStream(new FileOutputStream("D:\\log.txt")));
        ServerSocket ss=null;
        Socket s=null;  
        InputStream in=null;
        //while(true) {
	        try { 
	        	ss = new ServerSocket(6678);
	            //s=new Socket("192.168.88.6", 6678);
	        	System.out.println("waiting client connect");
	        	s = ss.accept();
	        	System.out.println("connect success");
	            String savePath="D:"+File.separator+"olclog"+File.separator;//"D:"+File.separator+"test"+File.separator;  
	            //String savePath = "C:"+File.separator+"Users"+File.separator+"Administrator"+File.separator+"Desktop"+File.separator+"olclog";
	            in=s.getInputStream();  
	            int size=10*1024;  
	            byte[] buf=new byte[size];  
	            int len=-1;  
	            byte[] bs=new byte[size];  
	            while((len=in.read(buf, 0, size))!=-1){  
	                writeData(buf,0,len,savePath,bs);  
	                  
	            }  
	        	System.out.println("accept file data success");  
	            if(out!=null){  
	                out.flush();  
	                out.close();  
	            }  
	        } finally {  
	            if(in!=null)  
	            in.close();  
	            if(s!=null)  
	            s.close();  
	        }  
       // }
    }  
  
    static FileOutputStream out=null;  
    static long count=0;//计算是否完成数据的读取,开始下一条命令  
    static int cmd=-1;  
      
    static int bsl=0;  
    private static void writeData(byte[] buf,int off, int len,String savePath,byte[] bs) throws Exception{  
        if(len-off==0)return;  
        System.out.println("偏移量:"+off+"命令"+cmd+"数量:"+count);  
        int i=off;  
        if(count==0l){//如果一条命令的数据已经读完就开始读取下一条命令  
            cmd=buf[i++];  
            System.out.println("获取命令:"+cmd);  
            count=-1l;  
            if(len-i==0)return;  
            writeData(buf,i,len,savePath,bs);  
        }else if(count==-1l){//读取文件(夹)名称的长度或文件的大小  
            System.out.println("获取长度");  
            switch (cmd){  
            case 0:  
                if(len-i+bsl<8){  
                    System.arraycopy(buf, i, bs, bsl, len-i);  
                    System.out.println("读取长度1:"+(len-i)+"  未读取完");  
                    bsl=len-i;  
                    i=0;  
                    return;  
                }  
                System.arraycopy(buf, i, bs, bsl, 8-bsl);  
                System.out.println("读取长度1:"+(8-bsl)+"  读取完");  
                count=bytesToLong(bs, 0);  
                i+=8-bsl;  
                bsl=0;  
                writeData(buf,i,len,savePath,bs);  
                break;  
            case 1:  
            case 2:  
                if(len-i+bsl<4){  
                    System.arraycopy(buf, i, bs, bsl, len-i);  
                    System.out.println("读取长度2:"+(len-i)+"  未读取完");  
                    bsl=len-i;  
                    i=0;  
                    return;  
                }  
                System.arraycopy(buf, i, bs, bsl, 4-bsl);  
                System.out.println("读取长度2:"+(4-bsl)+"  读取完");  
                count=bytesToInt(bs, 0);  
                i+=4-bsl;  
                bsl=0;  
                writeData(buf,i,len,savePath,bs);  
                break;  
            }  
        }else{//写入文件或创建文件夹、创建文件输出流  
            System.out.println("3");  
                switch (cmd){  
                case 0:  
                    System.out.println("写入文件");  
                    if(len-i-count>0){  
                        try{  
                            System.out.println("写入文件      长度:"+count+"文件写入完成");  
                            out.write(buf, i, (int)count);  
                            i+=count;  
                            count=0;  
                            out.flush();  
                        }finally{  
                            if(out!=null)out.close();  
                        }  
                        writeData(buf,i,len,savePath,bs);  
                    }else{  
                        System.out.println("写入文件      长度:"+(len-i)+"文件写入没有完成");  
                        out.write(buf,i,len-i);  
                        count-=len-i;  
                        i=0;  
                    }break;  
                case 1:  
                    if(len-i-count<0){  
                        System.out.println("获取文件名字:"+(len-i)+"写入没有完成    剩余长度"+count);  
                        System.arraycopy(buf, i, bs, bsl, len-i);  
                        bsl+=len-i;  
                        count-=bsl;  
                        i=0;  
                        return;  
                    }else{  
                        System.out.println("获取文件名字:"+(count-bsl)+"写入完成    剩余长度");  
                        System.arraycopy(buf, i, bs, bsl, (int)count);  
                        String name=new String(bs,0,(int)count+bsl);  
                        System.out.println("文件:"+savePath+name);  
                        out=new FileOutputStream(savePath+name);  
                        bsl=0;  
                        i+=count;  
                        count=0;  
                        writeData(buf,i,len,savePath,bs);  
                    }  
                    break;  
                case 2:  
                    if(len-i-count<0){  
                        System.out.println("获取文件夹名字:"+(len-i)+"写入没有完成    剩余长度"+count);  
                        System.arraycopy(buf, i, bs, bsl, len-i);  
                        bsl+=len-i;  
                        count-=bsl;  
                        i=0;  
                        return;  
                    }else{  
                        System.out.println(len+"   "+count+"   "+bsl+"  ");  
                        System.out.println("获取文件夹名字:"+(count-bsl)+"写入完成    剩余长度");  
                        System.arraycopy(buf, i, bs, bsl, (int)count);  
                        String name=new String(bs,0,bsl+(int)count);  
                        File file=new File(savePath+name);  
                        bsl=0;  
                        i+=count;  
                        count=0;  
                        if(!file.exists()){  
                            file.mkdirs();  
                        }  
                        System.out.println("文件夹:"+savePath+name);  
                        writeData(buf,i,len,savePath,bs);  
                    }  
                    break;  
                }  
        }  
          
    }  
      
    private static int bytesToInt(byte[] buf,int off){  
        int i=0;  
        i=i|((buf[off]&255)<<24);  
        i=i|((buf[off+1]&255)<<16);  
        i=i|((buf[off+2]&255)<<8);  
        i=i|(buf[off+3]&255);  
        return i;  
    }  
      
    private static long bytesToLong(byte[] buf,int off){  
        long i=0;  
        i=i|(((long)buf[off]&255)<<56)  
        |(((long)buf[off+1]&255)<<48)  
        |(((long)buf[off+2]&255)<<40)  
        |(((long)buf[off+3]&255)<<32)  
        |(((long)buf[off+4]&255)<<24)  
        |(((long)buf[off+5]&255)<<16)  
        |(((long)buf[off+6]&255)<<8)  
        |((long)buf[off+7]&255);  
        return i;  
    }  
}  
客户端:

package test;  
  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.InputStream;  
import java.io.OutputStream;  
import java.net.ServerSocket;  
import java.net.Socket;  
  
public class TCPClient {  
      
    static int size=10*1024;  
    static byte[] buf=new byte[size];  
    static int len=-1;  
    public static void main(String[] args) throws Exception{  
        ServerSocket ss=null;  
        OutputStream out=null;  
        Socket s=null;  
        try {  
            //ss=new ServerSocket(1024);
        	s = new Socket("192.168.88.6",6678);
            System.out.println("等待客户端连接");  
            //s=ss.accept();  
            System.out.println("连接成功");  
//          InputStream in=s.getInputStream();  
            out=s.getOutputStream();  
              
            long start=System.currentTimeMillis();  
            System.out.println("开始发送文件");  
            String fileName="D:"+File.separator+"APLog_2017_0328_084931";//"I:"+File.separator;  
            if(!fileName.endsWith(File.separator)){  
                fileName+=File.separator;  
            }  
            File file=new File(fileName);  
            String parent=file.getParent();  
            if(parent==null){  
                File[] fs=file.listFiles();  
                for(int i=0;i<fs.length;i++){  
                    if(fs[i].isHidden())  
                    {  
                        System.out.println("隐藏文件"+fs[i].getAbsolutePath()+",不会被发送");  
                        continue;  
                    }  
                    test(fs[i],out,fs[i].getParent());  
                }  
            }else{  
                test(file,out,parent);  
            }  
            System.out.println("文件发送成功"+(System.currentTimeMillis()-start)+"ms");  
//          out.write("接受成功".getBytes());  
            out.flush();  
        } finally {  
            if(out!=null)out.close();  
            if(s!=null)s.close();  
            if(ss!=null)ss.close();  
        }  
    }  
      
    private static void test(File file,OutputStream out,String sendFileName)throws Exception{  
        FileInputStream in=null;  
        String fname=file.getAbsolutePath();  
        String name=fname.replace(sendFileName, "");  
        if(file.isDirectory()){  
            File[] fs=file.listFiles();  
            out.write(new byte[]{(byte)2}, 0, 1);//2:文件夹名  
            int fileLength=name.getBytes().length;  
            out.write(intToBytes(fileLength),0,4);//文件名的长度  
            out.write(name.getBytes(),0,name.getBytes().length);//文件名  
            System.out.println("文件夹:"+name+"   "+name.length());  
            out.flush();  
            for(int i=0;i<fs.length;i++){  
                if(fs[i].isHidden())  
                {  
                    System.out.println("隐藏文件"+fs[i].getAbsolutePath()+",不会被发送");  
                    continue;  
                }  
                test(fs[i],out,sendFileName);  
            }  
        }else{  
            out.write(new byte[]{(byte)1}, 0, 1);//1:文件名  
            int fileLength=name.getBytes().length;  
            out.write(intToBytes(fileLength),0,4);//文件夹名的长度  
            out.write(name.getBytes(),0,name.getBytes().length);//文件夹名  
            System.out.println("文件:"+name+"   "+name.length()+"  "+file.length());  
            out.flush();  
            in=new FileInputStream(file);  
            out.write(new byte[]{(byte)0}, 0, 1);//0表示文件数据  
            out.write(longToBytes(file.length()),0,8);//文件的长度  
            out.flush();  
            while((len=in.read(buf,0,size))!=-1){  
                out.write(buf,0,len);  
                out.flush();  
            }  
            in.close();  
        }  
    }  
      
    private static byte[] intToBytes(int i){  
        byte[] b=new byte[4];  
        b[0]=(byte)((i>>>24)&255);  
        b[1]=(byte)((i>>>16)&255);  
        b[2]=(byte)((i>>>8)&255);  
        b[3]=(byte)(i&255);  
        return b;  
    }  
      
    private static byte[] longToBytes(long i){  
        byte[] b=new byte[8];  
        b[0]=(byte)((i>>>56)&255);  
        b[1]=(byte)((i>>>48)&255);  
        b[2]=(byte)((i>>>40)&255);  
        b[3]=(byte)((i>>>32)&255);  
        b[4]=(byte)((i>>>24)&255);  
        b[5]=(byte)((i>>>16)&255);  
        b[6]=(byte)((i>>>8)&255);  
        b[7]=(byte)(i&255);  
        return b;  
    }  
  
} 



  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值