客户端代码
void sendFiles(int socket, const string& directory) {
//获取文件数量
//socket传入socket()函数返回值,directory传入文件夹目录
try {
vector<string> fileList;
DIR* dir = opendir(directory.c_str());
if (dir) {
dirent* entry;
while ((entry = readdir(dir)) != nullptr) {
if (entry->d_type == DT_REG) {
fileList.push_back(entry->d_name);
}
}
closedir(dir);
}
//文件数量
int filesCount = fileList.size();
//发送文件数量
send(socket, &filesCount, sizeof(filesCount), 0);
char buffer[BUFFER_SIZE];
for (const string& filename : fileList) {
string filePath = directory + "/" + filename;
FILE* file = fopen(filePath.c_str(), "rb");
if (file) {
int fileNameLength = filename.length();
//发送文件名长度
send(socket, &fileNameLength, sizeof(fileNameLength), 0);
//发送文件名
send(socket, filename.c_str(), fileNameLength, 0);
cout<<fileNameLength<<endl;
//cout << "Sending file: " << filename << endl;
fseek(file, 0, SEEK_END);
long fileSize = ftell(file);
rewind(file);
char fileSizeString[7];
snprintf(fileSizeString, sizeof(fileSizeString), "%06ld", fileSize);
//发送文件大小
send(socket, fileSizeString, 6, 0);
//发送文件
while (true) {
int bytesRead = fread(buffer, 1, sizeof(buffer), file);
if (bytesRead > 0) {
send(socket, buffer, bytesRead, 0);
} else {
break;
}
}
fclose(file);
cout << "File sent: " << filename << endl;
}
}
//close(socket);
//cout<<"close yes"<<endl;
} catch (exception& e) {
cerr << "Exception: " << e.what() << endl;
}
}
服务端代码
private static void receiveFiles(Socket servertSocket, File saveDir) {
try {
//byte[] buffer = new byte[4096];
byte[] inputByte = null;
//int bytesRead;
InputStream inputStream = serverSocket.getInputStream();
// 读取文件数量
byte[] filesCountBytes = new byte[4];
inputStream.read(filesCountBytes);
int filesCount = byteArrayToInt(filesCountBytes)/1024/1024/16;
for (int i = 0; i < filesCount; i++) {
// 读取文件名长度
byte[] fileNameLengthBytes = new byte[4];
inputStream.read(fileNameLengthBytes);
int fileNameLength = byteArrayToInt(fileNameLengthBytes)/1024/1024/16;
//读取文件名
byte[] fileNameBytes = new byte[fileNameLength];
inputStream.read(fileNameBytes);
String fileName = new String(fileNameBytes);
//读取文件大小
byte[] fileSizeBytes = new byte[6];
inputStream.read(fileSizeBytes);
int fileSize =Integer.parseInt(new String(fileSizeBytes));
// System.out.println(fileSize);
Log.i("Server", "Receiving file: " + fileName);
//保存文件
File file = new File(saveDir, fileName);
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int length=0;
while (fileSize > 0) {
if (new DataInputStream(inputStream) != null) {
if(fileSize-1024<0)
inputByte = new byte[fileSize];
else
inputByte = new byte[1024];
length = inputStream.read(inputByte, 0, inputByte.length);
}
if (length == -1) {
break;
}
bos.write(inputByte, 0, length);
fileSize -= length;
bos.flush();
}
bos.close();
fos.close();
Log.i("Server", "File saved: " + file.getAbsolutePath());
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}