简体   繁体   English

将文件从客户端发送到服务器

[英]Send a file from Client to a Server

I'm developing a client/server program in C. The server send to a client a txt file, but the name is like corrupt. 我正在用C开发客户端/服务器程序。服务器向客户端发送一个txt文件,但名称像损坏的一样。 The content is good, only the name is not good. 内容不错,只是名字不好。

Can someone tell me why? 有人可以告诉我为什么吗? Thank you! 谢谢!

This is the code who send the file: 这是发送文件的代码:

fd = open(appoggio1, O_RDONLY);
if (fd < 0) {
  fprintf(stderr, "unable to open '%s': %s\n", appoggio1, strerror(errno));
  exit(1);
}
while ((nread = read(fd, buffer2, sizeof(buffer2))) > 0) 
    {
        write(servers_fd, buffer2, nread);
            read(servers_fd,buffer2,sizeof(char));
    }

    printf("Trasmissione completata con successo\n\n");

    write(servers_fd,fine,strlen(fine)); 
    read(servers_fd,fine,strlen(fine));
close(fd);

This is the code who receive the file: 这是接收文件的代码:

fd = open(nomefile, O_CREAT | O_WRONLY, 0755);

    if (fd < 0) 
    {
        fprintf(stderr, "errore open(): %s\n", strerror(errno));
        exit(errno);
    }
while ((nread = read(conn_fd, buffer, sizeof(buffer))) > 0)
{
    if(!strncmp(buffer,fine,7))
        break;        
    write(fd, buffer, nread);
    write(conn_fd,buffer,sizeof(char));
}
write(conn_fd,fine,strlen(fine));

} }

The problem is with your protocol. 问题出在您的协议上。

You send the file and then the name. 您发送文件,然后发送名称。 But the client has no way of knowing when the file ends and the name begins. 但是客户端无法知道文件何时结束以及名称开始。

You can fix it by first sending the length of the name and then the actual name: 您可以先发送名称的长度,然后发送实际名称,以解决此问题:

#include <arpa/inet.h>

// Write the file name with length marker
uint32_t nameLength = htonl(strlen(fine));
write(servers_fd, &nameLength, sizeof nameLength); 
write(servers_fd, fine, strlen(fine)); 

// Write the actual file.

And in the client: 在客户端中:

#include <arpa/inet.h>

uint32_t nameLength;
read(conn_fd, &nameLength, sizeof nameLength);
nameLength = ntohl(nameLength);

read(conn_fd, fine, nameLength);
fine[nameLength] = '\0';  // Add nul-terminator to file name.

// Read the rest of the file

htonl and ntohl convert numbers to network byte order, enabling your code to work even if the client and server use different byte orders (big/little endianness). htonlntohl将数字转换为网络字节顺序,即使客户端和服务器使用不同的字节顺序(大/小字节序),代码也可以正常工作。

Note: Unless you use a size marker for the actual file as well, the client won't know how big it is, and the connection will only be good for one file download. 注意:除非您也为实际文件使用大小标记,否则客户端将不知道文件的大小,并且该连接仅适用于一个文件的下载。

Note2 : I have ignored the possibility that the size and file names might be divided into more than one network packets. 注意2 :我忽略了大小和文件名可能被分成多个网络数据包的可能性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM