java socket收发文件

介绍

实现收发文件功能:

server端:启动服务,等待client连接,接收数据,并写入文件
client:启动客户端,连接服务器,发送文件

server 简单版

public class Server3 {
    public static int PORT=9527;
    public static void main(String[] args) {
        byte[] buff=new byte[1024];
        try {
            ServerSocket ss=new ServerSocket(PORT);
            System.out.println("启动成功,端口:"+PORT);
            Socket s=ss.accept();
            InputStream is=s.getInputStream();

            FileOutputStream fos=new FileOutputStream(System.currentTimeMillis()+".jpg");

            int len=is.read(buff);
            while(len!=-1) {
                fos.write(buff,0,len);
                len=is.read(buff);
            }

            fos.close();
            is.close();
            s.close();
            ss.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

client

public class Client3 {
    public static void main(String[] args) {
        byte[] buff=new byte[1024];
        try {
            Socket s=new Socket("127.0.0.1",Server.PORT);
            System.out.println("连接成功!");
            OutputStream os=s.getOutputStream();

            FileInputStream fis=new FileInputStream("C:\\Users\\mym\\Desktop\\可删除\\20181106171429773.png");
            int len=fis.read(buff);
            while (len!=-1){
                os.write(buff,0,len);
                len=fis.read(buff);
            }
            System.out.println("发送成功!");

            fis.close();
            s.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

server 优化版

public class Server4 {
    public static int PORT=9527;
    public static void main(String[] args) {
        try {
            ServerSocket ss=new ServerSocket(PORT);
            System.out.println("启动成功,端口:"+PORT);
            while(true) {
                Socket s=ss.accept();
                new Thread(new ReceiveFile(s)).start();
            }
//            ss.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

class ReceiveFile implements Runnable{
    private Socket s;

    public ReceiveFile(Socket s) {
        this.s = s;
    }

    @Override
    public void run() {
        byte[] buff=new byte[1024];
        try {
            InputStream is = s.getInputStream();

            FileOutputStream fos=new FileOutputStream(System.currentTimeMillis()+".jpg");

            int len=is.read(buff);
            while(len!=-1) {
                fos.write(buff,0,len);
                len=is.read(buff);
            }

            fos.close();
            is.close();
            s.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

高级版

server

public class Server5 {
    public static int PORT=9527;
    public static void main(String[] args) {
        try {
            ServerSocket ss=new ServerSocket(PORT);
            System.out.println("启动成功,端口:"+PORT);
            while(true) {
                Socket s=ss.accept();
                new Thread(new ReceiveFile2(s)).start();
            }
//            ss.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
public class ReceiveFile2 implements Runnable{
    private Socket s;

    public ReceiveFile2(Socket s) {
        this.s = s;
    }

    @Override
    public void run() {
        System.out.println(String.format("客户端:%s:%d 连接到服务器", s.getInetAddress().getHostAddress(),s.getPort()));
        byte[] buff=new byte[1024];
        try {
            InputStream is = s.getInputStream();
            OutputStream os=s.getOutputStream();

            //接收请求头并解析
            int len=is.read(buff);
            String fileInfo=new String(buff,0,len);
            System.out.println("接收到客户端指令:"+fileInfo);
            String[] array=fileInfo.split(";");
            String fileName=array[0].split(":")[1];
            String fileLenStr=array[1].split(":")[1];
            int receiveFileLen=Integer.parseInt(fileLenStr);

            //发送ready,告知客户端可以发送
            os.write("ready".getBytes());
            os.flush();
            System.out.println("向客户端发送:ready");

            //创建文件
            FileOutputStream fos=new FileOutputStream(fileName);
            System.out.println("创建文件:"+fileName);
            System.out.println("准备接收数据...");
            //接收文件
            len=is.read(buff);
            int totalLen=len;
            while(len!=-1) {
                fos.write(buff,0,len);
                if(totalLen==receiveFileLen){
                    break;
                }
                len=is.read(buff);
                totalLen+=len;
            }

            fos.close();
            System.out.println("接收完毕!");

            //发送接收成功!
            os.write("success".getBytes());
            os.flush();
            System.out.println("向客户端发送:success");

            is.close();
            s.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

client

public class Client4 {
    public static void main(String[] args) {
        byte[] buff=new byte[1024];
        try {
            Socket s=new Socket("127.0.0.1",Server.PORT);
            System.out.println("连接到服务器!");
            OutputStream os=s.getOutputStream();
            InputStream is=s.getInputStream();

            File file=new File("C:\\Users\\mym\\Desktop\\【《TensorFlow深度学习》】.pdf");
            //发送请求头,包含文件名、文件大小
            String fileInfo=String.format("file_name:%s;file_len:%d",file.getName(),file.length());
            os.write(fileInfo.getBytes());
            os.flush();
            System.out.println("向服务器发送:"+fileInfo);

            //等待接收服务器是否准备好
            int len=is.read(buff);
            String receiveStr=new String(buff,0,len);
            System.out.println("接收到服务器指令:"+receiveStr);

            if("ready".equals(receiveStr)) {
                //发送文件
                FileInputStream fis = new FileInputStream(file);
                len = fis.read(buff);
                while (len != -1) {
                    os.write(buff, 0, len);
                    len = fis.read(buff);
                }
                os.flush();
                System.out.println("发送文件完毕!");
                len = is.read(buff);
                receiveStr=new String(buff, 0, len);
                System.out.println("接收到服务器指令:"+receiveStr);
                if("success".equals(receiveStr)){
                    System.out.println("文件上传成功!");
                }
                fis.close();
            }
            s.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

原文出处:/show_1EF62QfrGhhQ.html