通过读取二进制文件,将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)。
答案 0 :(得分:1)
strcpy(szbuffer,concat(current_bit,szbuffer));
字符串操作函数(如strcpy
,strlen
等)仅适用于本身不能包含\0
的文本数据,因为它们会将\0
视为字符串的结尾。但PDF是二进制的,因此可以包含\0
。因此,strcpy
只会将数据复制到第一个\0
。
除此之外,使用UDP传输文件是一个坏主意,除非您确保可以处理丢失的数据包,重复数据包和数据包重新排序。更好地使用已经关注所有这一切的TCP。