我想通过套接字将文件从Linux服务器发送到Windows客户端,问题是我收到的字节多于发送的字节数。
服务器代码--------------------------------------------- -
if (resultEnviarLongitud = send(ClientSocket,GotFileSize.c_str(),1024,0)<0){
cout<<endl<<"Error mandando la longitud! "<<endl;
}
rewind(fs);
while ((len = fread(Buffer,1,1024, fs)) > 0)
{
if((resultEnviar = send(ClientSocket,Buffer,1024,0)) < 0){
printf("ERROR: Failed to send file %s.\n", nombreArchivoADescargar.c_str());
break;
}
sumEnviada+=len;
}
send(ClientSocket,"Hi",sizeof(Buffer),0);
cout<<"Bytes enviados: "<<sumEnviada<<endl;
strcpy(data, "");
cout<<endl<<"ARCHIVO MANDADO EXITOSAMENTE!"<<endl;
rutaArchivoADescargar.clear();
客户端代码-----------------------------------------
if (resultRecibirLongitud = recv(sock, Buffer, sizeof(Buffer), 0) > 0)
{
LongitudArchivo = atoi(Buffer);
cout<<endl<<"Longitud Archivo a Recibir: " <<LongitudArchivo<<endl;
}
FILE *fp=fopen("imagen.jpg","wb");
if (fp==NULL){
cout<<"Error al crear archivo."<<endl;
}else{
bzero(Buffer2, 1024);
int fr_block_sz = 0;
int contador=0;
//shutdown(sock, SD_SEND); I HAVE TO USE IT?
while((fr_block_sz = recv(sock, Buffer2, 1024, 0)) >= 0)
{
if (fr_block_sz == 0) break;
if ( strcmp (Buffer,"Hi") == 0) break;
int write_sz = fwrite(Buffer2, 1, 1024, fp);
if(write_sz < fr_block_sz)
{
printf("File write failed on server.\n");
}
bzero(Buffer2, 1024);
contador+=fr_block_sz;
if (contador >= LongitudArchivo)break;
bzero(Buffer2, 1024);
}
cout<<endl<<"Numero de bytes recibidos: "<<contador<<endl<<endl;
if(fr_block_sz < 0)
{
printf("Error receiving file from client to server.\n");
}
printf("Ok received from client!\n");
fclose(fp);
}
谢谢,
答案 0 :(得分:3)
while ((len = fread(Buffer,1,1024, fs)) > 0)
{
if((resultEnviar = send(ClientSocket,Buffer,1024,0)) < 0)
您的一个问题是,即使您fread
字节较少,也始终发送1024字节的缓冲区。 (请注意,1348656向上舍入到最接近的1024的倍数是1349632.)
所以,在写作方面你需要类似的东西:
while ((len = fread(Buffer,1,1024, fs)) > 0)
{
if((resultEnviar = send(ClientSocket,Buffer,len,0)) < 0)
并且在阅读方面你需要类似的东西:
while((fr_block_sz = recv(sock, Buffer2, 1024, 0)) >= 0)
{
// ...
int write_sz = fwrite(Buffer2, 1, fr_block_sz, fp);
您的初始send
也存在问题,因为您总是发送1024个字节而不检查这是c_str
返回的实际长度。