基于客户端和服务端的文件上传

一、客户端

public class Client {
    public static void main(String[] args) throws IOException {
        // 创建客户端对象
        Socket socket = new Socket("localhost", 8888);
        // 创建网络输出流对象
        OutputStream outputStream = socket.getOutputStream();
        // 读取本地文件
        BufferedInputStream in = new BufferedInputStream(new FileInputStream("D:/aaa/1.jpg"));
        int len;
        byte[] bytes = new byte[1024];
        while ((len = in.read(bytes)) != -1) {
            outputStream.write(bytes, 0, len);
        }
        socket.shutdownOutput(); // todo 上传完成关闭!
        // 获取网络输入流
        InputStream inputStream = socket.getInputStream();
        len = inputStream.read(bytes);
        System.out.println(new String(bytes, 0, len));
        outputStream.close();
        socket.close();
    }
}

二、服务端继承Runnable接口,实现多线程

public class ServerRunnableImpl implements Runnable {
    private Socket accept;
    public ServerRunnableImpl(Socket accept) {
        this.accept = accept;
    }
    @Override
    public void run() {
        try {
            // 接收客户端传来的文件
            InputStream inputStream = accept.getInputStream();
            // 创建高效输出流对象
            BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream("d:/ccc/" + System.currentTimeMillis() + "3.jpg"));
            int len;
            byte[] b = new byte[1024];
            while ((len = inputStream.read(b)) != -1) {
                outputStream.write(b, 0, len);
            }
            // 创建网络输出流,写给客户端
            OutputStream out = accept.getOutputStream();
            out.write("上传成功".getBytes());
            inputStream.close();
            outputStream.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

三、服务端启用线程池

//  服务器接收客户端传来的文件
//  服务器接收客户端传来的文件
public class ServerRunnablePool {
    public static void main(String[] args) throws IOException {
        System.out.println("服务器已经开启");
        // 创建服务器对象
        ServerSocket server = new ServerSocket(8888);

        while (true) {
            Socket accept = server.accept();
            ServerRunnableImpl serverRunnable = new ServerRunnableImpl(accept);
            ExecutorService pool = Executors.newFixedThreadPool(2); // 创建线程池
            pool.submit(serverRunnable);
        }
    }
}

发表评论