-1

这可能是一个简单的解决方案,但基本上我使用 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");
    }
4

2 回答 2

1

When you are reading data:

n = read(sockfd,buffer,BLOCKSIZE);
if (n < 0)
  error("Error: reading from socket.");
int checksum = checksumv(buffer,BLOCKSIZE);

you need to respect the number of bytes that read() says it placed into buffer - it may read fewer than BLOCKSIZE number of bytes before returning.

Also, I don't see where the checksum is sent (or received) - I only see the file data being sent. How are you comparing checksums?

Finally, since TCP is a streaming protocol, you'll need to have some way to indicate to receiver when the file data is finished such as by sending the size ahead of the file data, or having some 'out of band' indication.

于 2013-04-30T06:31:42.917 回答
0

您没有正确累积校验和,但您不需要所有这些复杂性来复制文件:

byte buffer[8192];
while ((count = fread(buffer, sizeof buffer, 1, fp)) > 0)
{
    n = write(sock,buffer4,count);
    if (n < 0)
      error("ERROR writing to socket");
    checksum += checksumv(buffer, count); // or possibly ^=, it depends how your checksum is supposed to accumulate
}
于 2013-04-30T06:14:06.933 回答