android java Socket多文件发送

来源:互联网 发布:sas编程技术教程 编辑:程序博客网 时间:2024/05/17 23:46

前一阵子做一个android的类似飞鸽的东西,用到了Socket发送单个或者多个文件,在此分享出来,还望对大家有所帮助。

 

发送方核心代码:

     

for (int i = 0;i < files.length; i++) {                byte[] namebyte = files[i].getName().getBytes("UTF-8");                long size = files[i].length();                int nameLength = namebyte.length;                fileChannel = new FileInputStream(files[i]).getChannel();                ByteBuffer buffer = ByteBuffer.allocate(1024);                buffer.clear();                buffer.putInt(4+8+nameLength);                buffer.putInt(nameLength);                buffer.put(namebyte);                buffer.putLong(size);                buffer.flip();                while(buffer.hasRemaining()){                    sc.write(buffer);                }                long count = 1024*1024;                long read = 0L;                while(read < size){                    if(size - read < count)                        count = size - read;                    read += fileChannel.transferTo(0+read, count, sc);                    System.out.println("read:"+read);                }                fileChannel.close();                if(i < files.length -1){                    sc.write(ByteBuffer.wrap(new byte[]{1}));                    System.out.println(1);                }                else                    sc.write(ByteBuffer.wrap(new byte[]{0}));            }


    接收方核心代码,由于发送的时候文件的信息,如:文件名和文件大小是分开发送的,所以接收的时候也是分开接收的,多个文件的时候接收方式一个一个接收的。

   

private void parseHead(int headlength) {        buffer = ByteBuffer.allocate(headlength);        try {            while(buffer.position() < buffer.capacity())              clientChannel.read(buffer);            buffer.flip();            byte[] filenamebyte = new byte[buffer.getInt()];            buffer.get(filenamebyte);            fileName = new String(filenamebyte,"UTF-8");            fileSize = buffer.getLong();        } catch (IOException e) {            e.printStackTrace();        }    }private void parseBody(long size) {        long read = 0L;        long count = 8192;        FileChannel fileChannel = null;        try {            fileChannel = new FileOutputStream(path + fileName)                    .getChannel();            System.out.println(fileName);            while (read < size) {                if (size - read < count)                    count = size - read;                read += fileChannel                        .transferFrom(clientChannel, 0 + read, count);            }        } catch (IOException e) {            e.printStackTrace();        }finally{            try {                fileChannel.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }

 

好了,希望对你有所帮助,有事去了。不行的话留下邮箱,我发送源码给你。

原创粉丝点击