我想使用此命令将使用GET请求收到的所有内容保存到文件中:
./client http://example.com/1.jpg > image.jpg
我的recv_buf
是2000个字节。
// Generate HTTP request
sprintf(send_buf, "%s %s %s%s %s%s", "GET", path, "HTTP/1.1\r\n",
"HOST:", hostname, "\r\n\r\n");
send_len = strlen(send_buf); //length of request to send
bytes_send = send(sockfd, send_buf, send_len, 0);
if (bytes_send <= 0)
{
perror("nothing sended\n");
exit(1);
}
printf("Bytes send: %d\nSended message: %s\n", bytes_send, send_buf);
// receive data
do {
bytes_recv = recv(sockfd, recv_buf, sizeof(recv_buf), 0);
if (bytes_recv <= 0)
{
perror("connection closed or error");
close(sockfd);
freeaddrinfo(results);
exit(0);
}
printf("Bytes received: %d\n", bytes_recv);
//write(1, recv_buf, bytes_recv);
} while (bytes_recv > 0);
我到目前为止我可以接收数据直到最后,但我不知道如何将所有“包”以正确的顺序组合到一个缓冲区,然后将其作为二进制数据(图像)保存到文件中。 / p>
输出是:
./client https://example.com/1.jpg
Bytes received: 2000
Bytes received: 1792
Bytes received: 2000
Bytes received: 1792
Bytes received: 639
connection closed or error: Success
答案 0 :(得分:0)
您可以按如下方式使用realloc和memcpy
:
unsigned char* buf = 0;
int bufsize = 0;
do {
bytes_recv = recv(sockfd, recv_buf, sizeof(recv_buf), 0);
if (bytes_recv <= 0)
{
perror("connection closed or error");
close(sockfd);
freeaddrinfo(results);
exit(0);
}
buf = realloc(buf, bufsize + bytes_recv);
memcpy(buf + bufsize, recv_buf, bytes_recv);
bufsize += bytes_recv;
} while (bytes_recv > 0);
buf
将不包含已读取的bufsize
个字节。或者写入文件并使用malloc
并再次读取该文件。