【问题标题】:Unable to send pdf through binary with UDP无法使用 UDP 通过二进制发送 pdf
【发布时间】:2014-11-11 16:36:16
【问题描述】:

通过读取二进制文件将 pdf 文件从客户端发送到服务器时遇到了一些问题。我正在使用 UDP 传输,当我将文本文件从客户端发送到服务器时,我完全接收到文件而没有任何错误,但是当我发送 PDF 时,打开文件时出现错误。以下是我对发送者和接收者的要求:

发件人:

file = fopen(file_name_char, "rb"); //read in binary here

int size_count = (file_size / (BUFFER_SIZE - 2)) + 1; //amount of times to loop

            for (int i = 0; i < size_count; i++)
            {
                memset(szbuffer, 0, BUFFER_SIZE);
                fread(szbuffer, sizeof(char), BUFFER_SIZE - 2, file); //Read for the buffersize -2 (reserve a spot for bit and \0)

                strcpy(szbuffer, concat(current_bit, szbuffer));

                send_with_select(s, szbuffer, (struct sockaddr*)&sa1, (struct sockaddr*)&sa1, sa1_length, current_bit, "file contents", 0); //send file contents

                file_size = file_size - BUFFER_SIZE + 2; //decrease size

                client_bit = change_bit(client_bit);
                *current_bit = bit_string(client_bit);
                //change bit
            }
            fclose(file);

对于我的 UDP 传输,我在每个缓冲区前面加上一个序列号来模拟 Stop N Wait 协议

接收者:

int size_count = (file_size / (BUFFER_SIZE - 2)) + 1; //amount of times to loop

            for (int i = 0; i < size_count; i++)
            {
                file = fopen(file_name, "ab"); 
                //open file for writing

                memset(szbuffer, 0, BUFFER_SIZE);
                receive_packet_transfer(s, szbuffer, (struct sockaddr*)&sa_in, (struct sockaddr*)&sa_in, sa_length, current_bit, content, "file contents", client_bit); //receive file contents

                client_bit = change_bit(client_bit);
                *current_bit = bit_string(client_bit);
                //change bit

                if (file_size <= BUFFER_SIZE)
                    fwrite(content, sizeof(char), file_size, file);
                else
                    fwrite(content, sizeof(char), BUFFER_SIZE - 2, file); //write into file

                file_size = file_size - BUFFER_SIZE + 2; //decrease size
                fclose(file);
            }

我已经使用 sendto() recvfrom() 方法实现了 send_with_select() 和 receive_packet_transfer()。他们基本上做同样的事情,但等待 ACK 或超时(使用 select)。

【问题讨论】:

    标签: c++ sockets networking udp binaryfiles


    【解决方案1】:

    strcpy(szbuffer, concat(current_bit, szbuffer));

    strcpystrlen 等字符串操作函数仅适用于本身不能包含\0 的文本数据,因为它们认为\0 是字符串的结尾。但是 PDF 是二进制的,因此可以包含\0。因此strcpy 只会将数据复制到第一个\0

    除此之外,使用 UDP 传输文件不是一个好主意,除非您确保可以处理丢失的数据包、重复的数据包和数据包重新排序。最好使用已经关心这一切的 TCP。

    【讨论】:

    • Ulrich 我需要使用 UDP 进行分配。谢谢,这很有意义。你知道是否有一种方法可以在二进制中复制或者我应该使用结构来避免尝试在缓冲区前面加上一个序列位(在我的情况下)
    猜你喜欢
    • 2012-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    • 1970-01-01
    • 2014-03-31
    • 2012-01-02
    相关资源
    最近更新 更多