public class MultiTranslate implements Impl{
private ExecutorService executorService = Executors.newFixedThreadPool(5);
private String parentPath;
@Override
public void sendFile(File file, List<InetSocketAddress> list) {
parentPath = file.getParent();
for(InetSocketAddress sa : list) {
sendFile(file, sa);
}
}
public void sendFile(File file, InetSocketAddress sa) {
if(file.isFile()){
executorService.execute(() -> {
try{
Socket socket = new Socket(sa.getAddress(),sa.getPort());
DataInputStream dis = new DataInputStream(new FileInputStream(file));
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
dos.writeInt(1);// 文件数量
dos.writeUTF(file.getAbsolutePath().replace(parentPath, ""));// 文件名
dos.writeLong(file.length());// 文件大小
byte[] b = new byte[1024];
int c = -1;
while((c = dis.read(b)) != -1){
dos.write(b);// 文件字节
}
dos.flush();
dis.close();
dos.close();
socket.close();
}catch(IOException e){e.printStackTrace();}
});
} else {
for(File f : file.listFiles()){
sendFile(f, sa);
}
}
}
}
Socket 多线程 多文件传输
最新推荐文章于 2023-03-19 15:54:27 发布