鉴于曾经写过相关文章,这里就不再详细介绍了,关于详细的介绍可以参考我之前的文章
HTTP协议初识·中篇-CSDN博客
一个简单的设置套接字的过程,也当成是复习一下下了
代码
#include <iostream>
#include <cstdio>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
int main()
{
// 1.创建套接字
int sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(socket < 0)
{
perror("socket error");
return -1;
}
// 2.绑定套接字
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(8085);
addr.sin_addr.s_addr = inet_addr("0.0.0.0");
socklen_t len = sizeof(struct sockaddr_in);
int ret = bind(sockfd, (struct sockaddr*)&addr, len);
if(ret < 0)
{
perror("bind error");
return -1;
}
// 3.设置监听套接字
ret = listen(sockfd, 5);
if(ret < 0)
{
perror("listen error");
return -1;
}
// 4.获取新连接
while (1)
{
int newfd = accept(sockfd, nullptr, 0);
if(newfd < 0)
{
perror("accept error");
return -1;
}
char buf[1024] = {0};
int ret = recv(newfd, buf, 1024, 0);
if(ret < 0)
{
perror("recv error");
close(newfd);
continue;
}else if (ret == 0)
{
perror("peer shutdown!");
close(newfd);
continue;
}
std::string body = "<html><body><h1>Hello World</h1></body></html>";
std::string rsp = "HTTP/1.1 200 OK\r\n";
rsp += "Content-Length: " + std::to_string(body.size()) + "\r\n";
rsp += "Content-Type: text/html\r\n";
rsp += "\r\n";
rsp += body;
ret = send(newfd, rsp.c_str(), rsp.size(), 0); // 0 阻塞式发送
if(ret < 0)
{
perror("send error!");
close(newfd);
continue;
}
close(newfd);
}
close(sockfd);
return 0;
}
测试成功