使用scket API在C ++中以客户端 - 服务器发送文件

时间:2014-04-20 08:36:10

标签: c++ sockets tcp client-server

我正在做能够发送和接收文件的客户端和服务器。但我无法找到任何可用于实现目的的有用功能。

在客户端,我告诉服务器要下载哪个文件,在哪个端口和服务器上告诉端口,并以kB / s为单位限制下载速度。我知道怎么做连接和周围的东西,但我真的不知道如何选择文件,如何发送它以及如何接收它+如何设置下载速度限制。 (我应该使用套接字API和TCP协议)

1 个答案:

答案 0 :(得分:0)

这是你可以从哪里开始的。

服务器

/*Receive File from Client */
#define LENGTH 512
    char* fr_name = "/file.jpg";
    FILE *fr = fopen( fr_name, "wb");
    if( fr == NULL)
        printf("File %s Cannot be opened file on server.\n", fr_name);
    else
    {
        bzero( revbuf, LENGTH); 
        int fr_block_sz = 0;

        bpt::ptime start, stop;
        start = bpt::microsec_clock::local_time();
        int totalBytes = 0;
        double transferRate = 0.0;

        while((fr_block_sz = recv( nsockfd, revbuf, LENGTH, 0)) > 0) 
        {
            stop = bpt::microsec_clock::local_time();
            bpt::time_duration dur = stop - start;
            double seconds = dur.total_milliseconds() / 1000.0;
            totalBytes += fr_block_sz;
            transferRate = totalBytes / seconds; // b/s

            int write_sz = fwrite( revbuf, sizeof(char), fr_block_sz, fr);
            if( write_sz < fr_block_sz)
            {
                error( "File write failed on server.\n");
            }
            bzero( revbuf, LENGTH);
            if ( fr_block_sz == 0 || fr_block_sz != 512) 
            {
                break;
            }
        }
        if(fr_block_sz < 0)
        {
            if (errno == EAGAIN)
            {
                printf("recv() timed out.\n");
            }
            else
            {
                fprintf(stderr, "recv() failed due to errno = %d\n", errno);
                exit(1);
            }
        }
        printf("Ok received from client!\n");
        fclose(fr); 
    }

客户端

FILE *fs = fopen(fs_name, "rb");
    if(fs == NULL)
    {
        printf("ERROR: File %s not found.\n", fs_name);
        exit(1);
    }

    bzero(sdbuf, LENGTH); 
    int fs_block_sz;

    bpt::ptime start, stop;
    start = bpt::microsec_clock::local_time();
    int totalBytes = 0;
    double transferRate = 0.0;

    while((fs_block_sz = fread(sdbuf, sizeof(char), LENGTH, fs)) > 0)
    {
        if(send(sockfd, sdbuf, fs_block_sz, 0) < 0)
        {
            fprintf(stderr, "ERROR: Failed to send file %s. (errno = %d)\n", fs_name, errno);
            break;
        }
        stop = bpt::microsec_clock::local_time();
        bpt::time_duration dur = stop - start;
        double seconds = dur.total_milliseconds() / 1000.0;
        totalBytes += fs_block_sz;
        transferRate = totalBytes / seconds; // b/s

        bzero(sdbuf, LENGTH);
    }

您可以使用<time.h>

中的标准实用程序代替提升
#include <time.h>
time_t start,end;
time (&start);
.
.
.
<your code>
.
.
.
time (&end);
double dif = difftime (end,start);
printf ("Elasped time is %.2lf seconds.", dif );