C++中使用TCP传文件
在两个文件中都定义文件头和用到的宏:
#define MAX_SIZE 10 #define ONE_PAGE 4096 struct FileHead { char str[260]; int size; };
在客户端发送接收阶段:
//1.发送文件头 char path[260] = {0}; cout<<"请输入文件路径"<<endl; cin>>path; //截取文件名 char* ptemp = path; while(*ptemp++ != '\0'); while(*(--ptemp) != '\\'); ptemp++; fstream fs; fs.open(path,fstream::in|fstream::binary); fs.seekg(0,fstream::end);//以最后的位置为基准不偏移 int nlen = fs.tellg();//取得文件大小 fs.seekg(0,fstream::beg); FileHead fh; fh.size = nlen; memcpy(fh.str,ptemp,MAX_PATH); nlen = send(sockConnect ,(char*)&fh,sizeof(fh),0); //2,.如果接受到的内容为是 char szResult[MAX_SIZE] = {0}; recv(sockConnect,szResult,sizeof(szResult),0); char szBuf[ONE_PAGE] ={0}; if(0 == strcmp(szResult,"是")) { //读文件 while(!fs.eof()) { fs.read(szBuf,ONE_PAGE); int len = fs.gcount(); //if(len == 0 ) break; send(sockConnect,szBuf,len,0); } } //3.关闭文件流 fs.close();
在服务器端,接收和发送阶段
char str[1024] = {0}; int nlen; nlen = recv(sockWaiter,(char*)&fh,sizeof(fh),0); cout<<"是否要接受文件"<<endl; cin>>str; send(sockWaiter ,str,sizeof(str),0); char szPath[MAX_SIZE] = {0}; cout<<"请输入要存储的路径"<<endl; cin>>szPath; char szPathName[MAX_SIZE] = {0}; sprintf(szPathName,"%s%s",szPath,fh.str);//拼接路径和文件名 cout<<szPathName<<endl; fstream fs; fs.open(szPathName,fstream::out|fstream::binary|fstream::trunc);//以空文件的形式打开 int FileSize = fh.size; int len; char content[ONE_PAGE] = {0}; while(FileSize) { len = recv(sockWaiter,content,ONE_PAGE,0); if(len > 0) { fs.write(content,len); FileSize -= len; } } fs.close();