Socket 文件字节传输 CS架构示例

Socket 文件字节传输 CS架构示例

客户端

[TOC]
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;

public class SocketClientTest extends Socket {
    private  final String SERVER_IP="127.0.0.1";
    private final int SERVER_PORT=9019;
    private Socket client;
    private FileInputStream fis;
    private DataOutputStream dos;

    //创建客户端,并指定接收的服务端IP和端口号
    public SocketClientTest() throws IOException {
        this.client=new Socket(SERVER_IP,SERVER_PORT);
        System.out.println("成功连接服务端..."+SERVER_IP);
    }

    //向服务端传输文件
    public void sendFile(String url) throws IOException {
        File file=new File(url);
        try {
            fis = new FileInputStream(file);
            //BufferedInputStream bi=new BufferedInputStream(new InputStreamReader(new FileInputStream(file),"GBK"));
            dos = new DataOutputStream(client.getOutputStream());//client.getOutputStream()返回此套接字的输出流
            //文件名、大小等属性
            dos.writeUTF(file.getName());
            dos.flush();
            dos.writeLong(file.length());
            dos.flush();
            // 开始传输文件
            System.out.println("======== 开始传输文件 ========");
            byte[] bytes = new byte[1024];
            int length = 0;

            while ((length = fis.read(bytes, 0, bytes.length)) != -1) {
                dos.write(bytes, 0, length);
                dos.flush();
            }
            System.out.println("======== 文件传输成功 ========");
        }catch(IOException e){
            e.printStackTrace();
            System.out.println("客户端文件传输异常");
        }finally{
            fis.close();
            dos.close();
        }
    }
    public static void main(String[] args) {
        try {
            SocketClientTest client = new SocketClientTest(); // 启动客户端连接
            client.sendFile("D:\\file\\work\\test\\a.pdf"); // 传输文件
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

服务端

import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServerTest {

    private static final int SERVER_PORT = 9019; // 服务端端口
    private ServerSocket server;
    private Socket socket;
    private DataInputStream dis;
    private FileOutputStream fos;

    public SocketServerTest() throws Exception {
        server=new ServerSocket(SERVER_PORT);
    }

    public void task() throws IOException {
        System.out.println("======== 等待连接 ========");
        Socket socket = server.accept();
        System.out.println(" Ip:"+socket.getInetAddress()+"已连接");
        try {
            dis = new DataInputStream(socket.getInputStream());
            // 文件名和长度
            String fileName = dis.readUTF();
            long fileLength = dis.readLong();
            File directory = new File("D:\\file\\work");
            if(!directory.exists()) {
                directory.mkdir();
            }
            File file = new File(directory.getAbsolutePath() + File.separatorChar + fileName);

            fos = new FileOutputStream(file);
            System.out.println("file。。。。。。。。。。。。。。"+file);
            System.out.println("fileName。。。。。。。。。。。。。。"+fileName);

            System.out.println("======== 开始接收文件 ========");
            byte[] bytes = new byte[1024];
            int length = 0;
            while((length = dis.read(bytes, 0, bytes.length)) != -1) {
                fos.write(bytes, 0, length);
                fos.flush();
            }

            System.out.println("======== 文件接收成功 ========");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(fos != null)
                    fos.close();
                if(dis != null)
                    dis.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        try {
            SocketServerTest server = new SocketServerTest(); // 启动服务端
            server.task();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

服务端:文件传输新开线程

import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server extends ServerSocket {

    private static final int SERVER_PORT = 9019; // 服务端端口

    private ServerSocket server;

    public Server() throws Exception {
        server=new ServerSocket(SERVER_PORT);
    }

    /**
     * 使用线程处理每个客户端传输的文件
     * @throws Exception
     */
    public void load() throws Exception {
        while (true) {
            System.out.println("-----------等待连接-------- ");
            Socket socket = server.accept();//接收连接服务端的客户端对象
            System.out.println("ip" + socket.getInetAddress() + "已连接");
            new Thread(new Transfer(socket),"thread1").start();// 每接收到一个Socket就建立一个新的线程来处理它
            System.out.println(Thread.currentThread().getName());
        }
    }

    /**
     * 处理客户端传输过来的文件线程类
     */
    class Transfer implements Runnable {

        private Socket socket;
        private DataInputStream dis;
        private FileOutputStream fos;

        public Transfer(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try {
                dis = new DataInputStream(socket.getInputStream());

                // 文件名和长度
                String fileName = dis.readUTF();
                long fileLength = dis.readLong();
                File directory = new File("E:/xn");
                if(!directory.exists()) {
                    directory.mkdir();
                }
                File file = new File(directory.getAbsolutePath() + File.separatorChar + fileName);
                System.out.println("file"+file);
                fos = new FileOutputStream(file);

                // 开始接收文件
                byte[] bytes = new byte[1024];
                int length = 0;
                while((length = dis.read(bytes, 0, bytes.length)) != -1) {
                    fos.write(bytes, 0, length);
                    fos.flush();
                }
                System.out.println("======== 文件接收成功 [File Name:" + fileName + "] ");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if(fos != null)
                        fos.close();
                    if(dis != null)
                        dis.close();

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static void main(String[] args) {
        try {
            Server server = new Server(); // 启动服务端
            server.load();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

上次修改时间:2022-09-11 00:12:35

>