#include "Util.hpp"
#include "Protocol.hpp"
#include <pthread.h>
class Sock{
private:
int sock;
int port;
public:
Sock(const int &port_):port (port_),sock(-1)
{}
void Socket()
{
sock=socket(AF_INET,SOCK_STREAM,0);
if(sock<0){
cerr << "socket error " << endl;
exit(2);
}
int opt = 1;
setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
}
void bind()
{
struct sockaddr_in local;
local.sin_family = AF_INET;
local.sin_addr.s_addr = htonl(INADDR_ANY);
local.sin_port = htons(port);
if(bind(sock,(struct sockaddr*)&local,sizeof(local))<0){
cerr << "bind error "<< endl;
exit(3);
}
}
void Listen()
{
const int backlog = 10;
if(listen(sock,backlog)<0){
cerr << “listen error " << endl;
exit(4);
}
}
int Accept(){
int sockaddr_in peer;
socklen_t len = sizeof(peer);
int fd = accept(sock,(struct sockaddr*)&peer,&len);
if(fd<0){
cerr << "accept error" << endl;
return -1;
}
cout << " get a new link " << endl;
return fd; }
~Sock()
{}
};
#define DEFAULT_PROT 8080
class HttpSever{
private:
Sock sock;
public:
HttpSever(int port=DEFAULT_PORT):sock(port)
{}
void InitHttpSever()
{
sock.Socket();
sock.bind();
sock.Listen();
}
void Start()
{
for(;;){
int sock_ = sock.Accept();
if(sock_ >=0){
pthread_t tid;
int* p = new int (sock_); pthread_create(&tid,nullptr,Entry::HandlerRequest,p);
}
}
}
};
Protocol.hpp
#pragma once
#include <string>
#include <sstream>
#include <iostream>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unstd.h>
#include <stdlib.h>
using namespace std;
class HttpRequest{
private:
string request_line;//请求行
string request_header;//请求报头
string request_blank;//请求空行
string request_body;//正文长度
private:
string method;
string uri;
string version;
public:
HttpRequest()
{
}
bool MethodIsLegal()
{
}
void RequestLineParse()//解析
{
//GET /index.html http/1.1
stringstream ss(request_line);
ss >> method >> uri >> version;
}
string &GetRequestLine()
{
return request_line;
}
~HttpRequest()
{
}
};
class HttpResponse{
private:
string response_line;
string response_header;
string response_blank;
string response_body;
public:
HttpResponse()
{
}
~HttpResponse()
{
}
};
class EndPoint{
//读请求
private:
int sock;
public:
Endpoint(int sock_)
{
}
int RecvLine(string &line)// \n \r \r\n
{
char c = 'X';
while(c!='\n'){
ssize_t s = recv(sock,&c,1,0);
if(s>0){
if(c == '\r'){
//\r or \r\n
if(recv(sock,&c,1,MSG_PEEK)>0){
if(c=='\n){
recv(sock,&c,1,0);
}
else{
c='\n';
}
}
else{
c='\n';
}
}
line.push_back(c);
}
else{
c='\n';
line.push_back(c);
}
}
return line.size();
}
void RecvRequestLine(HttpRequest *rq)
{
RecvLine(rq->GetRequestLine());
}
~Endpoint()
{
}
};
class Entry{
public:
static void *HandlerRequest(void *args)
{
int *p = (int*)args;
int sock = *p;
EndPoint *ep = new EndPoint(sock);
HttpRequest *rq = new HttpRequest();
HttpResponse *rsp = new HttpResponse();
ep->RecvRequestLine(rq);
rq->RequestLineParse();
if(!rq->MethodIsLegal()){
}
delete rq;
delete rsp;
delete ep;
delete p;
}
};