c++ - 通过 TCP/IP 连接发送二进制文件

标签 c++ c file-io malloc winsock

我将在这里重新表述整个问题,以便它可以回答。

我能够在同一台机器上完美地复制二进制文件,而不是使用套接字,而只是制作一个简单的复制功能。尝试实现此代码以复制到 TCP/IP 连接上,但无法使其正常工作。

FILE *filehandle = fopen("imagefile.jpg", "rb");
FILE *dest  =fopen("imagecopy.jpg", "wb");    // copied image file
fseek(filehandle, 0, SEEK_END);
unsigned long filesize = ftell(filehandle);
char *buffer = (char*)malloc(sizeof(char)*filesize);
rewind(filehandle);
int bytesread = fread(buffer, sizeof(char), filesize, filehandle);
for( int i=0; i<filesize; i++ )
{
    fputc(buffer[i], filehandle);    // copies all the contents to dest
}

上面的代码非常适合在计算机上复制图像文件,但是在服务器上实现复制时,就很难实现了。

我正在尝试将图像文件从服务器发送到客户端,这两个文件都是用 C 手动制作的。要发送的文件的长度服务器仅在发送文件时才为服务器所知,因此在服务器中动态生成缓冲区,如下所示:

服务器

fseek(filehandle, 0, SEEK_END);
long filesize = ftell(filehandle);    // file could be 11000bytes
char *buffer = (char*)malloc(sizeof(char)*filesize);    // char buffer with 11000 bytes to store the data from the file.
// then I call the send() function
rewind(filehandle);    // go back to beginning
send(clientsocket, buffer, filesize, 0);    // this is being sent perfectly, no errors because in the actual code, I am checking for errors

客户

// here is where I don't understand how to dynamically allocate the 11000 bytes to store the data in a client buffer
// the filesize is not necessarily going to be 11000 so need to dynamically allocate
// I did the following:
#define BUFSIZE 10
FILE *filehandle = fopen("imagefile.jpg", "wb");    // image file created by client
char *buffer = (char*)malloc(sizeof(char)*BUFSIZE);
int bytesread = recv(buffer, 1, strlen(buffer), 0);
if( bytesread > 0 )
{
    printf("Bytes read: %d\n", bytesread);    // bytes read is 5
    printf("Buffer: %s\n", buffer);    // but buffer shows all the binary text like it normally would
    // when I try to store buffer in a file, it doesn't put full buffer because only 5 characters are written
    for( int i=0; i<bytesread; i++ )
    {
        fputc(buffer[i], filehandle);    // this doesn't create full image
    }
}

如何动态分配服务器发送的11000字节?

最佳答案

您需要循环发送和接收。 send()recv() 都不能保证发送/读取您请求的字节数。

您还应该在文件数据之前发送文件大小,以便接收方知道需要多少字节以及何时停止读取。

尝试更像这样的东西:

服务器

bool senddata(SOCKET sock, void *buf, int buflen)
{
    unsigned char *pbuf = (unsigned char *) buf;

    while (buflen > 0)
    {
        int num = send(sock, pbuf, buflen, 0);
        if (num == SOCKET_ERROR)
        {
            if (WSAGetLastError() == WSAEWOULDBLOCK)
            {
                // optional: use select() to check for timeout to fail the send
                continue;
            }
            return false;
        }

        pbuf += num;
        buflen -= num;
    }

    return true;
}

bool sendlong(SOCKET sock, long value)
{
    value = htonl(value);
    return senddata(sock, &value, sizeof(value));
}

bool sendfile(SOCKET sock, FILE *f)
{
    fseek(f, 0, SEEK_END);
    long filesize = ftell(f);
    rewind(f);
    if (filesize == EOF)
        return false;
    if (!sendlong(sock, filesize))
        return false;
    if (filesize > 0)
    {
        char buffer[1024];
        do
        {
            size_t num = min(filesize, sizeof(buffer));
            num = fread(buffer, 1, num, f);
            if (num < 1)
                return false;
            if (!senddata(sock, buffer, num, 0))
                return false;
            filesize -= num;
        }
        while (filesize > 0);
    }
    return true;
}

FILE *filehandle = fopen("imagefile.jpg", "rb");
if (filehandle != NULL)
{
    sendfile(clientsocket, filehandle);
    fclose(filehandle);
}

客户

bool readdata(SOCKET sock, void *buf, int buflen)
{
    unsigned char *pbuf = (unsigned char *) buf;

    while (buflen > 0)
    {
        int num = recv(sock, pbuf, buflen, 0);
        if (num == SOCKET_ERROR)
        {
            if (WSAGetLastError() == WSAEWOULDBLOCK)
            {
                // optional: use select() to check for timeout to fail the read
                continue;
            }
            return false;
        }
        else if (num == 0)
            return false;

        pbuf += num;
        buflen -= num;
    }

    return true;
}

bool readlong(SOCKET sock, long *value)
{
    if (!readdata(sock, value, sizeof(value)))
        return false;
    *value = ntohl(*value);
    return true;
}

bool readfile(SOCKET sock, FILE *f)
{
    long filesize;
    if (!readlong(sock, &filesize))
        return false;
    if (filesize > 0)
    {
        char buffer[1024];
        do
        {
            int num = min(filesize, sizeof(buffer));
            if (!readdata(sock, buffer, num))
                return false;
            int offset = 0;
            do
            {
                size_t written = fwrite(&buffer[offset], 1, num-offset, f);
                if (written < 1)
                    return false;
                offset += written;
            }
            while (offset < num);
            filesize -= num;
        }
        while (filesize > 0);
    }
    return true;
}

FILE *filehandle = fopen("imagefile.jpg", "wb");
if (filehandle != NULL)
{
    bool ok = readfile(clientsocket, filehandle);
    fclose(filehandle);

    if (ok)
    {
        // use file as needed...
    }
    else
        remove("imagefile.jpg");
}

关于c++ - 通过 TCP/IP 连接发送二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25634483/

相关文章:

c - C 中的格式说明符不明确

c - 任意多项式 : C code

java - Eclipse 在 bin 目录中找不到文件

java - 如何在java中读取unicode编码的文件

c++ - 从 vector 中获取 n 个最佳元素?

c++ - C++中的互联网套接字

c - 当 fd 是一个普通文件时,linux 系统调用 read(fd, buf, count) 是否返回小于 count?

java - 重命名目录和一些包含文件/子目录

C++ Java static final 等价物

c++ - AC_CHECK_LIB在mingw64中失败