http.srv.cpp
#include "tcpsock.hpp"
#include <iostream>
#include <sstream>
int main(int argc, char*argv[])
{
TcpSock lis_sock;
lis_sock.Socket();
std::string ip = "0.0.0.0";
uint16_t port = 9000;
lis_sock.Bind(ip,port);
lis_sock.Listen();
while(1)
{
TcpSock new_sock;
lis_sock.Accept(&new_sock);
std::string buf;
new_sock.Recv(&buf);
std::cout<<"http requset["<<buf<<"]\n"<<std::endl;
//组织响应信息
std::string body = "<html><body><h1>X M L</h1></body></html>"; // 正文
std::string blank = "\r\n"; // 空行
std::stringstream header; // 头部
header << "Content-Length: "<<body.size()<<"\r\n"; // 正文长度字段
header <<"Content-Type: text/html\r\n"; // 正文类型字段,决定客户端如何处理正文
header << "Connection: close\r\n";//长短连接选择字段
std::string first = "HTTP/1.1 200 OK\r\n"; // 首行
std::string http_rsp = first+header.str()+blank + body;
new_sock.Send(http_rsp);
new_sock.Close();
}
return 0;
}
tcpsock.hpp
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <string>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
class TcpSock
{
public:
TcpSock():_sockfd(-1){}
bool Socket()
{
_sockfd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(_sockfd < 0)
{
perror("socket error\n");
return false;
}
return true;
}
bool Bind(std::string &ip, uint16_t port)
{
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = inet_addr(ip.c_str());
socklen_t len = sizeof(addr);
int ret = bind(_sockfd,(struct sockaddr*) &addr,len);
if(ret < 0)
{
perror("bind error\n");
return false;
}
return true;
}
bool Listen(int backlog = 10)
{
if(listen(_sockfd,backlog) < 0)
{
perror("listen error\n ");
return false;
}
return true;
}
bool Connect(std::string &ip, uint16_t port)
{
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = inet_addr(ip.c_str());
socklen_t len = sizeof(addr);
int ret = connect(_sockfd,(struct sockaddr*) &addr, len);
if(ret < 0)
{
perror("connect error\n");
return false;
}
return true;
}
bool Accept(TcpSock* sock)
{
int newfd = accept(_sockfd,NULL,NULL);
if(newfd < 0)
{
perror("accept error\n");
return false;
}
sock->_sockfd = newfd;
return true;
}
bool Recv(std::string *buf)
{
char temp[1024] = {0};
int ret = recv(_sockfd, temp,1024,0);
if(ret < 0)
{
perror("recv error\n");
}
else if(ret == 0)
{
std::cout<<"connect shutdown"<<std::endl;
return false;
}
buf->assign(temp,ret);
return true;
}
bool Send(std::string &data)
{
int ret = send(_sockfd,data.c_str(),data.size(),0);
if(ret < 0)
{
perror("send error\n");
return false;
}
return true;
}
bool Close()
{
if(_sockfd >= 0)
{
close(_sockfd);
_sockfd = -1;
}
return true;
}
private:
int _sockfd;
};