正确传输客户端 - 服务器套接字连接中的文件

时间:2015-02-26 09:03:50

标签: c sockets file-upload

我已经编写了以下用于从客户端发送文件的代码:

FILE *fp = fopen("video.mp4","rb");
        if(fp==NULL)
        {
            printf("File opern error");
            return 1;   
        } 

int bytesToWrite=84440670;
int bytesWritten=0; 
while(bytesWritten<bytesToWrite)
    {
        int m=minimum(256,bytesToWrite-bytesWritten);
        /* First read file in chunks of 256 bytes or the remaining bytes*/
        unsigned char *buff=malloc(sizeof(char)*m);
        bzero(buff, m);
        int nread = fread(buff,1,m,fp);
        printf("Bytes read %d \n", nread);  
        bytesWritten+=m;   

        /* If read was success, send data. */
        if(nread > 0)
        {
            printf("Sending \n");
            write(sockfd, buff, nread);
        }

        /*
         * There is something tricky going on with read .. 
         * Either there was error, or we reached end of file.
         */
        if (nread < 256)
        {
            if (feof(fp))
                printf("End of file\n");
            if (ferror(fp))
                printf("Error reading\n");
            break;
        }


    }

以及服务器接收的以下代码:

FILE *fp;
        fp = fopen("receive.mp4", "wb"); 
        if(NULL == fp)
        {
            printf("Error opening file");
            return 1;
        }
        int bytesToRead=84440670;
        /* Receive data in chunks of 256 or remaining bytes */
        int totalbytesread=0;
        while(totalbytesread < bytesToRead)
        {
            int m = minimum(256,bytesToRead-totalbytesread);
            char *recvBuff=malloc(sizeof(char)*m);
            bzero(recvBuff,m);
            bytesReceived = read(newsocfd, recvBuff,m );
            printf("Bytes received %d\n",bytesReceived);
            totalbytesread += bytesReceived;   
            fwrite(recvBuff, 1,bytesReceived,fp);
        }

        if(bytesReceived < 0)
        {
            printf("\n Read Error \n");
        }

发送对.txt文件正常工作,一些数据在发送其他格式时丢失(例如,某些结束秒的.mp4文件未被发送)。 我是socket编程的新手。任何帮助都将深表感谢。

1 个答案:

答案 0 :(得分:0)

完成接收后,您在服务器中缺少fclose(fp);。您也可以使用fflush(fp);来刷新内容。

此外,还有几个内存泄漏和不正确的错误处理。