欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java socket长连接传输文件

程序员文章站 2024-03-24 22:31:52
...

一个简单的demo,实现Java socket文件传输。线程就不写了,只为了实现文件传输。
前面四个字节表示文件大小(长度),后面为数据体,数据体往后五个字节表示文件后缀名,后缀名超过五个字节的,则为二进制文件,丢弃文件后缀。

服务端接收
下面是服务端代码:

package receptionData;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Test {

    public static void main(String[] args) {
        try {
            ServerSocket s = new ServerSocket(8896);
            Socket sc = s.accept();
            InputStream in = sc.getInputStream();
            int t = 1;
            while(true){
                byte[] lData = new byte[4];
                in.read(lData);
                int length = byteArrayToInt(lData);
                System.out.println("文件大小:"+length+"字节");
                byte[] dt2 = new byte[length];

                readData(in,dt2);

                byte[] type = new byte[5];

                in.read(type);

                String typeStr = new String(type);
                System.out.println("文件类型:"+typeStr.trim());
                File of = new File("D:/RRR"+t+"."+typeStr.trim());
                of.createNewFile();
                OutputStream o = new FileOutputStream(of);

                o.write(dt2);
                o.flush();
                o.close();
                t++;




            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    private static int byteArrayToInt(byte[] b) {
        return b[3] & 0xFF |
                (b[2] & 0xFF) << 8 |
                (b[1] & 0xFF) << 16 |
                (b[0] & 0xFF) << 24;
    }

    private static byte[] intToByteArray(int a) {
        return new byte[]{
                (byte) ((a >> 24) & 0xFF),
                (byte) ((a >> 16) & 0xFF),
                (byte) ((a >> 8) & 0xFF),
                (byte) (a & 0xFF)
        };
    }

    /**
     * 
     * @param in
     * @param bData
     * @throws IOException
     */
    private static void readData(InputStream in,byte[] bData) throws IOException{
        int off = 0;
        int length = bData.length;
        int readLength = 0;
        do{
            off = readLength+off;
            length = length-readLength;
            readLength = in.read(bData, off, length);
        }while(readLength!=length);
    }


}

客户端发送
下面是客户端代码:

package sendData;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Test {

    public static void main(String[] args) {
        try {
            Scanner sn = new Scanner(System.in);
            Socket s = new Socket("127.0.0.1",8896);
            OutputStream out = s.getOutputStream();
            while(true){
                System.out.println("请输入文件路径");
                String pathAndFileName = sn.nextLine();
                File f = new File(pathAndFileName);
                if(!f.exists()){
                    System.out.println("文件不存在");
                    continue;
                }else{
                    InputStream in = new FileInputStream(f);
                    int length = (int) f.length();
                    if(length>1024*1024*5){
                        System.out.println("文件过大");
                        continue;
                    }else{

                        String[] tempFileType = pathAndFileName.split("\\.");
                        String fileType = tempFileType[tempFileType.length-1];
                        byte[] typeData = fileType.getBytes();
                        byte[] sendTypeData = new byte[5];
                        if(typeData.length<5){
                            System.arraycopy(typeData, 0, sendTypeData, 0, typeData.length);
                        }

                        byte[] tempData = new byte[length];
                        in.read(tempData);
                        in.close();

                        byte[] lengthData = intToByteArray(length);
                        byte[] sendData = new byte[tempData.length+lengthData.length+sendTypeData.length];

                        System.arraycopy(lengthData, 0, sendData, 0, lengthData.length);
                        System.arraycopy(tempData, 0, sendData, lengthData.length, tempData.length);
                        System.arraycopy(sendTypeData, 0, sendData, lengthData.length+tempData.length, sendTypeData.length);

                        out.write(sendData);
                        out.flush();
                    }
                }
            }
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private static int byteArrayToInt(byte[] b) {
        return b[3] & 0xFF |
                (b[2] & 0xFF) << 8 |
                (b[1] & 0xFF) << 16 |
                (b[0] & 0xFF) << 24;
    }

    private static byte[] intToByteArray(int a) {
        return new byte[]{
                (byte) ((a >> 24) & 0xFF),
                (byte) ((a >> 16) & 0xFF),
                (byte) ((a >> 8) & 0xFF),
                (byte) (a & 0xFF)
        };
    }

}

每次最多只能发小于5M的文件,超过需要自己分批发送和接收数据。如果会上面的代码实现10G的传输应该也不难。

传输效果:
java socket长连接传输文件

传输了两个jpg,两个txt文件

接收到的文件:
java socket长连接传输文件

相关标签: socket文件传输