sockets - 如何在一个套接字 C++ 中发送和接收多个文件大小?
问题描述
我正在尝试开发一个客户端/服务器应用程序来共享文件..
1-客户端发送文件大小
2-客户端发送文件数据(名称+内容)
3-服务器recv文件大小
4-服务器recv文件数据(名称+内容)
我的代码适用于一个文件,我在问如何编辑它以便我可以发送和接收多个文件的大小?
任何人都可以帮助PLZ!
客户端代码:
cout << "[Client] Sending files name to the Server... " << endl ;
int i=0;
while(i<files_vector.size()){
/************ Read & Send filename *************/
string filename = files_vector[i].getFullNameFile();
string test = filename+"&&";
size_t nameLen = strlen(test.c_str());
if(filename == "." || filename == "..")
continue;
string path_file = cf.pathSrcFiles+filename;
std::ifstream infile(path_file, std::ifstream::binary);
int32_t sizef = files_vector[i].getTaille();
/*** Send file size to server ***/
char fsize[256];
sprintf(fsize, "%d", nameLen+sizef);
if(send(sock, fsize, sizeof(fsize),0) < 0){
perror("Error sending file size\n");
exit(1);
}
/**** Send file data ****/
char content_file[sizef];
bzero(content_file, sizef);
infile.read(content_file,sizef);
string concat = test+string(content_file);
char file[sizef];
strcpy(file, concat.c_str());
cout << "content : " << file << endl;
cout << "size : " << nameLen+sizef << endl;
if(send(sock, file, nameLen+sizef, 0) < 0)
{
cout << stderr << "ERROR: Failed to send file" << filename << "
(error no = " << errno << ")" << endl;
break;
}
bzero(content_file, sizef);
infile.close();
cout << "Ok File " << filename << " from Client was Sent!\n" << endl;
i++;
}
服务器代码:
char csize[256];
int rc;
int32_t fsize;
/** Receive file size **/
if(rc = recv(sock, csize, 256, 0)) < 0){
cout << "Error receiving file size" << endl;
exit(1);
}
csize[rc] = '\0';
fsize = atoi(csize);
int n = 0;
int bytes_read = 0;
char* file;
file = new char[fsize];
memset(file, 0, fsize);
/** Receive file data **/
while((n = recv(sock, file+bytes_read, fsize-bytes_read, 0) > 0) &&
(bytes_read < fsize)){
cout << "content : " << file << endl;
bytes_read += n;
memset(file, 0, fsize);
}
delete[] file;
解决方案
推荐阅读
- c - 通过填充单词的数组操作文件的单词(从文件中检索)
- go - json.Marshal set null
- excel - 使用 VBA 从 Excel 列表发送大量电子邮件
- java - Transverse 2D Jagged Array, Columns First
- spring - 使用 @PathVariable 提供 URL
- vuejs2 - Center floating button in vuetify
- python - 消息之间的延迟(重写之前)
- bash - 将所有文件夹的bin子目录添加到path
- php - 使用 Mysql PDO、jQuery、AJAX 和 PHP 7.0 进行内联编辑
- node.js - mongoose $text search for specific keys