2013-12-09 99 views
0

尝试读取块中的文件并通过TCP连接发送每个块。当读取/发送循环完成时,我发送确认消息。任何时候我的文件大于一个块,这几乎总是,确认消息永远不会到达。无法分辨这是因为它没有被发送或只是没有收到。它似乎被发送了,但我无法确定。对于小文件,这工作得很好。文件本身在所有情况下都能正确发送,但我也需要此确认消息发送。文件读取,未收到TCP消息

任何人都可以看到为什么这可能会发生?

   int header_size = sizeof("file,,") + sizeof(int); 
       int bytes_remaining, filesize; 
       fseek(fp1, 0L, SEEK_END); 
       filesize = bytes_remaining = ftell(fd); 
       fseek(fd, 0L, SEEK_SET); 

       int bytes_to_read; 

       if ((BUFFSIZE - header_size) < bytes_remaining) { 
        bytes_to_read = BUFFSIZE - header_size; 
       } else { 
        bytes_to_read = bytes_remaining; 
       } 

       while (bytes_read = fread(buffer, 1, bytes_to_read, fd) > 0) { 

        sprintf(message, "file,%d,%s", bytes_to_read, buffer); 
        send(sd, message, bytes_to_read + header_size, 0); 

        bytes_remaining -= bytes_to_read; 

        if ((BUFFSIZE - header_size) < bytes_remaining) { 
         bytes_to_read = BUFFSIZE - header_size; 
        } else { 
         bytes_to_read = bytes_remaining; 
        } 

        bzero(buffer, BUFFSIZE); 
       } 

       // send confirmation message 
       bzero(buf, 256); 
       sprintf(buf, "send_complete"); 
       send(sd, buf, 256, 0); 
       fprintf(stdout, "complete: %s\n", buf); 
+0

您是否检查发送的返回值? – fjc

回答

2

send(),就像write()fwrite并不能保证所有的数据被消耗。 您必须检查send()的返回值,以确定实际发送的字节数。

我猜你错过了确认消息,因为TCP输出缓冲区已满。