You need to enable JavaScript to run this app. Java Socket单客户端与服务端通过并行连接实现多文件传输问题咨询
优惠活动
大模型
产品
解决方案
定价
更多

Java Socket单客户端与服务端通过并行连接实现多文件传输问题咨询

单客户端服务端并行多连接传输文件解决方案

需求说明

需要实现单客户端与单服务端之间的并行连接,假设共有5个文件,需要通过并行连接同时发送,效果如下图:
客户端与服务端并行连接示意图
原有代码尝试创建2个连接发送2个文件,运行结果不符合预期,以下是问题原因和修正方案。

原代码核心问题

  • 客户端文件数据写完后没有手动flush也没有主动关闭输出流,BufferedOutputStream的缓冲数据没有完全发送到服务端,导致服务端一直阻塞等待数据
  • Server类中定义的存储路径E:\\DestinatioFolder\\拼写错误(少了字母n),和ClientHandler中的路径不一致,会导致文件写入失败
  • 单字节循环读写效率极低,大文件场景下性能极差
  • 没有做空值判断,比如源目录不存在时listFiles()返回null会触发空指针异常

修正后代码

服务端代码

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    // 统一存储路径,避免拼写不一致
    private static final String DIR = "E:\\DestinationFolder\\";

    public static void main(String[] args) throws IOException {
        // 预先创建目录,避免目录不存在导致写入失败
        File dirFile = new File(DIR);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        // 并行连接数,需要传5个文件改为5即可
        int connectionCount = 2;
        ServerSocket[] servSock = new ServerSocket[connectionCount];
        Socket[] sockets = new Socket[connectionCount];

        for (int i = 0; i < connectionCount; i++) {
            servSock[i] = new ServerSocket(5050 + i);
            sockets[i] = servSock[i].accept();
            System.out.println("新连接已建立:端口" + (5050 + i));
        }

        for (int i = 0; i < connectionCount; i++) {
            BufferedInputStream bis = new BufferedInputStream(sockets[i].getInputStream());
            DataInputStream dis = new DataInputStream(bis);
            Thread t = new ClientHandler(sockets[i], bis, dis);
            t.start();
        }
    }
}

class ClientHandler extends Thread {
    private static final String DIR = Server.DIR;
    private final BufferedInputStream bis;
    private final DataInputStream dis;
    private final Socket socket;
    // 缓冲区大小,可根据需求调整
    private static final int BUFFER_SIZE = 8192;

    public ClientHandler(Socket socket, BufferedInputStream bis, DataInputStream dis) {
        this.socket = socket;
        this.bis = bis;
        this.dis = dis;
    }

    @Override
    public void run() {
        BufferedOutputStream bos = null;
        try {
            long fileLength = dis.readLong();
            String fileName = dis.readUTF();
            System.out.println("开始接收文件:" + fileName + ",文件大小:" + fileLength + "字节");

            File file = new File(DIR + fileName);
            FileOutputStream fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);

            byte[] buffer = new byte[BUFFER_SIZE];
            int readLen;
            long totalRead = 0;
            while (totalRead < fileLength && (readLen = bis.read(buffer, 0, (int) Math.min(BUFFER_SIZE, fileLength - totalRead))) != -1) {
                bos.write(buffer, 0, readLen);
                totalRead += readLen;
            }
            bos.flush();
            System.out.println("文件接收完成:" + fileName);
        } catch (Exception e) {
            System.out.println("服务端异常:" + e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                if (bos != null) bos.close();
                if (dis != null) dis.close();
                if (socket != null) socket.close();
                System.out.println("连接已关闭");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

客户端代码

import java.io.*;
import java.net.Socket;

public class Client {
    private static final String SOURCE_DIR = "E:\\SourceFolder\\";

    public static void main(String[] args) throws IOException, InterruptedException {
        // 并行连接数,和服务端保持一致即可
        int connectionCount = 2;
        Socket[] sock = new Socket[connectionCount];
        for (int i = 0; i < connectionCount; i++) {
            sock[i] = new Socket("localhost", 5050 + i);
        }

        File[] files = new File(SOURCE_DIR).listFiles();
        // 空值判断,避免源目录不存在导致空指针
        if (files == null || files.length < connectionCount) {
            System.out.println("源目录文件不足,请检查路径配置");
            return;
        }
        sendFile(files, sock);
    }

    private static void sendFile(File[] files, Socket[] sock) throws InterruptedException, IOException {
        for (int i = 0; i < sock.length; i++) {
            BufferedOutputStream bos = new BufferedOutputStream(sock[i].getOutputStream());
            DataOutputStream dos = new DataOutputStream(bos);
            Thread t = new ClientThread(files[i], bos, dos);
            t.start();
        }
    }
}

class ClientThread extends Thread {
    private final BufferedOutputStream bos;
    private final DataOutputStream dos;
    private final File file;
    private static final int BUFFER_SIZE = 8192;

    public ClientThread(File file, BufferedOutputStream bos, DataOutputStream dos) {
        this.dos = dos;
        this.bos = bos;
        this.file = file;
    }

    @Override
    public void run() {
        BufferedInputStream bis = null;
        try {
            long length = file.length();
            dos.writeLong(length);
            String fileName = file.getName();
            System.out.println("开始发送文件:" + fileName + ",文件大小:" + length + "字节");
            dos.writeUTF(fileName);
            dos.flush();

            FileInputStream fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);

            byte[] buffer = new byte[BUFFER_SIZE];
            int readLen;
            while ((readLen = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, readLen);
            }
            bos.flush();
            System.out.println("文件发送完成:" + fileName);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bis != null) bis.close();
                if (dos != null) dos.close();
                if (bos != null) bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

补充说明

如果不需要多端口监听,也可以调整为服务端单端口accept多个连接实现并行传输,无需创建多个ServerSocket实例,逻辑上会更简洁。

内容的提问来源于stack exchange,提问作者Ismail Hossain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 22:45:01