这可能是一个简单的解决方案,但基本上我使用 TCP 将二进制文件逐个发送到另一个程序并检查以确保校验和匹配有效性。问题是收到的校验和绝不是除了提交的最后一部分(其余部分)之外发送的校验和。
发件人的代码片段是:
void* buffer = (void *)malloc(BLOCKSIZE+1);
if (!buffer)
error("Error: malloc error for buffer.\n");
fread(buffer, BLOCKSIZE, 1, fp_read); //read from binary file for the current block.
int checksum = checksum(buffer,BLOCKSIZE);
n = write(sockfd,buffer,BLOCKSIZE);
if (n < 0)
error("ERROR writing to socket");
对于接收器是:
void* buffer = (void *)malloc(BLOCKSIZE+1);
if (!buffer)
error("Error: malloc error for buffer.\n");
n = read(sockfd,buffer,BLOCKSIZE);
if (n < 0)
error("Error: reading from socket.");
int checksum = checksumv(buffer,BLOCKSIZE);
有人看出它有什么问题吗?校验和匹配的唯一部分是没有完全填满缓冲区的最后一块。
谢谢。
发件人的整个代码是:
FILE* fp_read = fopen("file.jpg", "rb");
if (fp_read == NULL)
error("Cannot open the file for peer piece download.");
fseek(fp_read, 0, SEEK_END);
unsigned long fileLen = ftell(fp_read);
fseek(fp_read, 0, SEEK_SET);
int checksum, loops = fileLen / BLOCKSIZE;
int remainder = fileLen % BLOCKSIZE;
int segment_num = loops+1;
void* buffer4 = (void *)malloc(BLOCKSIZE+1);
if (!buffer4)
error("Error: malloc error for buffer.\n");
int i, sent = 0;
for (i=1; i<=loops; i++)
{
fread(buffer4, BLOCKSIZE, 1, fp_read);
checksum = checksumv(buffer4,BLOCKSIZE);
n = write(sock,buffer4,BLOCKSIZE);
if (n < 0)
error("ERROR writing to socket");
}
if (remainder > 0)
{
//Allocate memory
void* buffer5 = (void *)malloc(remainder+1);
if (!buffer5)
error("Error: malloc error for buffer2.\n");
fread(buffer5, remainder, 1, fp_read);
checksum = checksumv(buffer5,remainder);
n = write(sock,buffer5,remainder);
if (n < 0)
error("ERROR writing to socket");
}