【发布时间】:2014-05-01 02:44:11
【问题描述】:
我正在尝试使用 C 中的套接字传输文件(在本例中为 .jpg 文件)。我有我的客户端和服务器代码,但我不知道为什么传输文件的字节数比原始文件多文件。代码如下:
服务器
/***************************************************
*
* Starting to send data file
*
***************************************************/
// Read the size of the file
recv(client.fd_client, &file.size_file, sizeof(int), 0);
recv(client.fd_client, &file.size_string, sizeof(int), 0);
recv(client.fd_client, &file.name_of_file, file.size_string, 0);
printf("Size of the file: %.3f kB\n", file.size_file/1000.);
printf("Receiving the file \"%s\"...\n", file.name_of_file);
if((file.fd_file = creat(file.name_of_file, S_IRWXU)) < 0) {
error("Can't open the file: ");
}
while(1) {
bzero(buffer, SIZE_BUF);
if((numb_bytes = read(client.fd_client, buffer, SIZE_BUF)) < 0) {
error("Can't read the file.");
}
write(file.fd_file, buffer, numb_bytes);
received += numb_bytes;
printf("Received: %.3fkB (%.3f/%.3f) kB\n", numb_bytes/1000., recibed/1000., file.size_file/1000.);
if(numb_bytes == 0)
break;
}
printf("Recibidos %.3f/%.3f kB\n", recibed/1000., file.size_file/1000.);
客户
/***************************************************
*
* Starting to send data file
*
***************************************************/
// Use strncpy!
strcpy(file.name_of_file, argv[3]);
file.fd_file = open(file.name_of_file, 0);
fstat(file.fd_file, &stat_file);
file.size_file = (unsigned int) stat_file.st_size;
file.size_string = (unsigned int) strlen(file.name_of_file) + 1;
printf("Size of the file: %.3f kB.\n", file.size_file/1000.);
printf("Sending the file \"%s\"...\n", file.name_of_file);
// Send data file
write(conection.sockfd, &file.size_file, sizeof(file.size_file));
write(conection.sockfd, &file.size_string, sizeof(file.size_string));
write(conection.sockfd, &file.name_of_file, sizeof(file.name_of_file));
while(1) {
sended += sendfile(conection.sockfd, file.fd_file, NULL, SIZE_BUF);
printf("send: %d\n", sended);
printf("num_bytes: %d\n", num_bytes);
if(sended == file.size_file)
break;
}
printf("Sended %.3f/%.3f kB\n", sended/1000., file.size_file/1000.);
我有几个问题:
- 大小和文件名的传输正确发生。我不明白为什么当我使用 ntohl 时它会给我垃圾。如果我是对的,由于 Little Endian 和 Big Endian,ntohl 和 ntos 都在使用套接字传输号码之前使用。那为什么会这样呢?
- 文件传输也正确发生,但客户端传输或服务器接收到的字节多于原始文件大小。我尝试传输图像,但无法打开。所以我尝试使用客户端的源代码,它可以很好地到达服务器(与以前一样有更多字节),但是当我打开它时,顶部有垃圾,然后是源代码。我认为传输发生得很好,但到达的字节比需要的多。谁能告诉我为什么会这样?
- 我正在以 1024kB 块传输文件,因为当我尝试通过一次调用发送整个文件时,我永远无法发送所有文件。我在互联网上看到了一些例子,他们修复了某种偏移量,直到它转移并从这一点开始再次转移。这是必要的吗?起初我认为它不是,因为我不使用它并且文件到达“好”,就像它自动知道从哪里继续读取文件一样。
【问题讨论】:
标签: c sockets file-transfer