项目名称:自主web服务器
实现环境:Linux、MySQL、浏览器
项目描述:
1、实现最基本的HTTP/1.0版本的web服务器,客户端能够使用GET、POST方法请求资源
2、服务器将客户请求的资源以html页面的形似呈现,并能够进行差错处理(如:客户请求的资源不存在时,服务 器能够返回一个404的页面)
3、服务器能进行简单的cgi运行。如当客户在表单中输入数据后,服务器能够将运行结果返回客户
4、能够通过页面对数据库进行操作,如增删查改等操作
应用技术:网络编程(TCP/IP协议,http协议),多线程技术,cgi技术,shell脚本,mysql
项目测试:
1、Linux设置为桥接模式后,外部浏览器可以正常访问。
2、刚开始设计的为单线程模式,每次只能允许一个外部访问。(增加线程池后,可以同时处理多个外部访问请 求)
3、运行cgi模式,编写的计算器可以正常运行。
4、服务器运行下载的html模板有延迟,但是能正常显示。(html模板内容太大,自己编写的html网页可以很快显示)
项目源码:
HttpServer.cc:
#include "HttpServer.hpp"
static void Usage(string proc)
{
cout<<"Usage: "<<proc<<" prot"<<endl;
}
//HttpServer 8080
int main(int argc,char *argv[])
{
if(argc!=2){
Usage(argv[0]);
exit(1);
}
HttpServer *htp=new HttpServer(atoi(argv[1]));
htp->InitHttpServer();
htp->Start();
delete htp;
return 0;
}
HttpServer.hpp:
#pragma once
#include <iostream>
#include <pthread.h>
#include "Protocol.hpp"
#include "Util.hpp"
#include "ThreadPool.hpp"
using namespace std;
class Sock{
private:
int sock;
int prot;
public :
Sock(const int &prot_):prot(prot_),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(prot);
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(){
struct 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 ... done"<<endl;
return fd;
}
~Sock(){
if(sock>=0){
close(sock);
}
}
};
#define DEFAULT_PORT 8080
class HttpServer{
private:
Sock sock;
//ThreadPool *tp;
public:
HttpServer(int port=DEFAULT_PORT):sock(port)//,tp(nullptr)
{}
void InitHttpServer(){
sock.Socket();
sock.Bind();
sock.Listen();
//tp=new ThreadPool(8);
//tp->InitThreadPool();
}
void Start(){
for(;;){
int sock_=sock.Accept();
if(sock_>=0){
pthread_t tid;
int *p=new int(sock_);
//Task t(p,Entry::HandlerRequest);
//tp->PushTask(t);
pthread_create(&tid,nullptr,Entry::HandlerRequest,p);
}
}
}
};
ThreadPool.hpp:
#pragma once
#include <iostream>
#include <queue>
#include <pthread.h>
using namespace std;
typedef void*(*handler_t)(void*);
class Task{
private:
int *sock_p;
handler_t handler;
public:
Task():sock_p(nullptr),handler(nullptr)
{ }
Task(int*sock_p_,handler_t h_):sock_p(sock_p_),handler(h_)
{ }
void Run()
{
handler(sock_p);
}
~Task()
{ }
};
class ThreadPool{
private:
int num;
queue<Task> q;
pthread_mutex_t lock;
pthread_cond_t cond;
public:
ThreadPool(int num_=8):num(num_)
{
pthread_mutex_init(&lock,nullptr);
pthread_cond_init(&cond,nullptr);
}
void LockQueue()
{
pthread_mutex_lock(&lock);
}
void UnlockQueue()
{
pthread_mutex_unlock(&lock);
}
bool HasTask()
{
return q.size()==0?false:true;
}
void ThreadWait()
{
pthread_cond_wait(&cond,&lock);
}
Task PopTask()
{
Task t=q.front();
q.pop();
return t;
}
void ThreadWakeUp()
{
pthread_cond_signal(&cond);
}
static void *ThreadRoutine(void *arg)
{
ThreadPool *tp=(ThreadPool*)arg;
while(true){
while(!tp->HasTask()){
tp->ThreadWait();
}
Task t=tp->PopTask();
tp->UnlockQueue();
t.Run();
}
}
void InitThreadPool()
{
pthread_t id;
for(auto i=0;i<num;i++){
pthread_create(&id,nullptr,ThreadRoutine,this);
}
}
void PushTask(const Task &t)
{
LockQueue();
q.push(t);
UnlockQueue();
ThreadWakeUp();
}
~ThreadPool()
{
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&cond);
}
};
Util.hpp:
#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <algorithm>
class Util{
public:
//static std::map<std::string,std::string> map_;
public:
static void StringToLower(std::string &s)
{
std::transform(s.begin(),s.end(),s.begin(),::tolower);
}
static void StringToUpper(std::string &s)
{
std::transform(s.begin(),s.end(),s.begin(),::toupper);
}
static void TansfromToVector(std::string &s,std::vector<std::string> &v)
{
size_t start=0;
while(1)
{
size_t pos=s.find("\n",start);
if(std::string::npos==pos){
break;
}
std::string sub_str=s.substr(start,pos-start);
v.push_back(sub_str);
start=pos+1;
}
}
static void MakeKV(std::string s,std::string &key,std::string &value)
{
size_t pos=s.find(": ",0);
if(std::string::npos==pos){
return ;
}
key=s.substr(0,pos);
value=s.substr(pos+2);
}
static int StringToInt(std::string s)
{
std::stringstream ss(s);
int result=0;
ss>>result;
return result;
}
static std::string IntToString(int i)
{
std::stringstream ss;
ss<<i;
return ss.str();
}
static std::string CodeToDec(int code)
{
switch(code){
case 200:
return "OK";
case 404:
return "NOT FOUND";
default:
return "Unknow";
}
}
static std::string SuffixToType(const std::string suffix)
{
std::string ct="Content_Type: ";
if(suffix==".html"){
ct+="text/html";
}else if(suffix==".js"){
ct+="application/x-javascript";
}else if(suffix=="css"){
ct+="text/css";
}else if(suffix==".jpg"){
ct+="image/jpeg";
}else if(suffix==".png"){
ct+="image/png";
}else if(suffix==".mp4"){
ct+="video/mpeg4";
}else{
ct+="text/html";
}
return ct;
}
};
testCgi.cc:
#include <iostream>
#include <unistd.h>
#include <string>
#include <stdio.h>
#include "Util.hpp"
using namespace std;
int GetData(string &str)
{
size_t pos=str.find('=');
if(string::npos!=pos){
return Util::StringToInt(str.substr(pos+1));
}
}
int main()
{
string args;
string method=getenv("METHOD");
if(method=="GET"){
args=getenv("QUERY_STRING");
}else if(method=="POST"){
//POST
string cl=getenv("CONTENT_LENGTH");
int content_length=Util::StringToInt(cl);
char c;
while(content_length--){
read(0,&c,1);
args.push_back(c);
}
}else{
//bug
}
size_t pos=args.find('&');
if(string::npos!=pos){
string first=args.substr(0,pos);
string second=args.substr(pos+1);
int data1=GetData(first);
int data2=GetData(second);
cout<<data1<<"+"<<data2<<"="<<data1+data2<<endl;
cout<<data1<<"-"<<data2<<"-"<<data1+data2<<endl;
cout<<data1<<"*"<<data2<<"*"<<data1+data2<<endl;
cout<<data1<<"/"<<data2<<"/"<<data1+data2<<endl;
}
cout<<"method: "<<method<<endl;
cout<<"args: "<<args<<endl;
cerr<<"cerr: method: "<<method<<endl;
cerr<<"cerr: args: "<<args<<endl;
return 0;
}
Makefile:
.PHONY:all
all:HttpServer testCgi
testCgi:testCgi.cc
g++ -o $@ $^
HttpServer:HttpServer.cc
g++ -g -o $@ $^ -std=c++11 -lpthread -g
.PHONY:clean
clean:
rm -f HttpServer testCgi