小智 5
你可以mmap文件并从那里写入套接字,你也可以使用fstat获取它的大小,如下所示:
fd = open(filename, O_RDONLY);
struct stat s;
fstat(fd, &s); // i get the size
adr = mmap(NULL, s.st_size, PROT_READ, MAP_SHARED, fd, 0); // i get the adress
write(socket, adr, s.st_size); // i send the file from this adress directly
Run Code Online (Sandbox Code Playgroud)
在完全发送之前,您可能只想发送文件的大小.您的客户可能希望向您发送他已获得良好规模并且他可以设法下载它.
一种想法可能是逐块读取文件,例如:
伪代码
#define CHUNK_SIZE 1000
void send(){
uint8_t buff[CHUNK_SIZE];
int actually_read;
while((actually_read = read(fd, buff, sizeof(buff)) > 0)
sendto(sock_fd, buff, actually_read, 0);
}
Run Code Online (Sandbox Code Playgroud)
您应该添加一些错误检查,但其想法是从要发送的文件中读取大量字节并发送该数量的字节。在服务器端,您需要做类似的事情,通过从套接字读取到达的块并将它们写入文件。buff如果您想处理多个文件传输,您可能需要添加一些元数据前缀来告诉服务器您正在传输哪个文件。由于 FTP 使用 TCP,因此您不必担心丢失数据。
再次强调,这只是一个想法。我想有多种方法可以做到这一点。