代码的用处:从服务器下载文件,先给服务器发送要下载的文件名,然后等待客户端发送信息是否找到这个文件
找到则发给客户段found,然后就开始接收文件,否者notfound,结束程序。
客户端代码:
环境是:Windows下QT软件,TCP协议
void file::judgeInfo()
{
QString tempname=lineEdit->text();
QByteArray tmppas = tempname.toLatin1();
char *filename = tmppas.data();
cout <<“file name is: ” << filename<< endl ;
char judge[10]=”found”;
if(send(sclient,filename,1024,0)<0) //文件名字
cout << “fail to send file name! ” << endl;
else
{
memset(judge,0,10);
while(1)
{
recv(sclient,judge,10,0); //接收服务器发过来的信息,即有没有这个文件
cout<<judge<<endl;
}
cout <<“———-> “<< judge <<endl;
if(strcmp(judge,”found”)==0) //发现则进行接收服务器发过来的文件
{
downloadRoot=downloadRoot+””/””+tempname;
QByteArray tmppas1 = downloadRoot.toLatin1();
char *recvfilename = tmppas1.data();
QMessageBox::warning(this,”warning—-“,recvfilename);
thread.recvfilesThead(sclient,recvfilename);
QMessageBox::information(this,”recv ok!”,”recv ok”);
thread.terminate();
}
else
QMessageBox::warning(this,”Waring”,”未找到这个文件!”);
}
}
服务器代码:
void sendfile(MA_Cli *tempsocket,char *filename)//接收的套接字和文件的名字
{
printf(“2 %d”,tempsocket);
FILE *fd=fopen(filename,”rb”);
char buff[SENDMAXSIZE];
int read_len=0;
if(fd==NULL) //查找是否有 文件
{
printf(“File: %s not found!\n”,filename);
send(tempsocket->MA_clientfd,”Not found !\n”,SENDMAXSIZE,0);
}
else
{
char found[]=”found”;
send(tempsocket->MA_clientfd,found,sizeof(found),0);//找到则发送found,然后就开始发送文件
memset(buff,0,SENDMAXSIZE);
while(read_len=(fread(buff,sizeof(char),SENDMAXSIZE,fd)))
{
if(send(tempsocket->MA_clientfd,buff,SENDMAXSIZE,0)<0)
{
printf(“Error failed send !\n”);
exit(1);
}
memset(buff,0,SENDMAXSIZE);
}
sleep(3);
send(tempsocket->MA_clientfd,”end”,3,0);
fclose(fd);
printf(“Transfer file finished !\n”);
}
}
出现的错误:
在客户端总是接收不到真正的found,接收输出的信息是个乱码
在服务器中,那个found一直发布过去,好像是阻塞在那里了,如果客户端关闭,found才发过去。