Http客户端
1. http协议格式
2. 构建http-server
代码路径,使用example/http-server, 选择tag7.7 版本的,直接make,如果有问题在makefile中添加-std=gnu99
https://gitee.com/mirrors/mongoose
3. 使用tcp模拟http-client
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <signal.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define SERVER_PORT 8000 //
#define SERVER_IP "127.0.0.1" //服务器IP地址
int main(int argc, const char *argv[])
{
int connect_fd = -1;
struct sockaddr_in server;
socklen_t saddrlen = sizeof(server);
memset(&server, 0, sizeof(server));
connect_fd = socket(AF_INET, SOCK_STREAM, 0);
if (connect_fd < 0)
{
printf("socket error!\n");
return -1;
}
server.sin_family = AF_INET;
server.sin_port = htons(SERVER_PORT);
server.sin_addr.s_addr = inet_addr(SERVER_IP);
if (connect(connect_fd, (struct sockaddr *)&server, saddrlen) < 0)
{
printf("connect failed!\n");
return -1;
}
printf("connect success \n");
char buf[256] = "GET / HTTP/1.1\r\n\r\n";
char rcvbuf[1024*1024] = {0};
while (1)
{
// printf(">");
// fgets(buf, sizeof(buf), stdin);
// if (strcmp(buf, "quit\n") == 0)
// {
// printf("client will quit!\n");
// break;
// }
write(connect_fd, buf, strlen(buf));
memset(rcvbuf, 0, 1024*1024);
int count = read(connect_fd, rcvbuf, 1024*1024);
if(count < 0)
{
printf("no recv data \n");
}
else
{
printf("recv data : %s\n", rcvbuf);
}
usleep(5*1000*1000);
}
close(connect_fd);
return 0;
}
// gcc ***.c
编译后直接运行./a.out即可
以上为http-client是如何运行的详解