3-4:一个简单的HTTP服务器
生活随笔
收集整理的這篇文章主要介紹了
3-4:一个简单的HTTP服务器
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
文章目錄
- HTTP服務(wù)器
HTTP服務(wù)器
我們使用瀏覽器請求某一個(gè)網(wǎng)頁時(shí),瀏覽器會(huì)向相應(yīng)的服務(wù)器發(fā)送請求,服務(wù)器得到請求后會(huì)將報(bào)文傳送回來,然后瀏覽器解析,就形成了我們所看見到的網(wǎng)頁
這里我們可以寫一個(gè)簡單的HTTP服務(wù)器去模擬一下這個(gè)過程,讓瀏覽器請求我的服務(wù)器然后返回相應(yīng)的報(bào)文。代碼如下,基本就是書寫tcp/ip的那一套邏輯
#include <iostream> #include <string> #include <cstring> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/socket.h> #include <sys/types.h> #include <stdlib.h> #include <unistd.h> #include <signal.h>using namespace std; class HttpServer {private:int _port;int _lsock;public:HttpServer(int port):_port(port),_lsock(-1){}void InitServer(){signal(SIGCHLD,SIG_IGN);_lsock=socket(AF_INET,SOCK_STREAM,0);if(_lsock < 0){cerr<<"scoket error"<<endl;exit(2);}struct sockaddr_in local;bzero(&local,sizeof(local));local.sin_family=AF_INET;local.sin_port=htons(_port);local.sin_addr.s_addr=INADDR_ANY;if(bind(_lsock,(struct sockaddr*)&local,sizeof(local)) < 0){cerr<<"socke bind error"<<endl;exit(3);}if(listen(_lsock,5) < 0){cerr<<"listen error"<<endl;exit(4);}}void echoHttp(int sock){char request[2048];size_t s=recv(sock,request,sizeof(request),0);//bug,后序還要做協(xié)議處理if(s > 0){request[s]=0;cout << request <<endl;string response="HTTP/1.0 200 OK\r\n";//響應(yīng)報(bào)頭首行response += "Content-type: text/html\r\n";//響應(yīng)正文,文件類型response +="\r\n";response +="<h1>This is a sample HttpServer!!!</h1>";send(sock,response.c_str(),response.size(),0);}close(sock);}void Start(){struct sockaddr_in peer;for(;;){socklen_t len=sizeof(peer);int sock=accept(_lsock,(struct sockaddr*)&peer,&len);if(sock < 0) {cerr<<"accept error"<<endl;continue;}cout<<"get a new connect"<<endl;if(fork()==0){close(_lsock);echoHttp(sock);exit(0);}close(sock);}}~HttpServer(){if(_lsock==-1){close(_lsock);}}};其中在echoHttp函數(shù)中,在拿到一個(gè)socket時(shí),我們將接受過來的請求報(bào)文保存在一個(gè)字符數(shù)組中,并輸出它。然后使用response這個(gè)字符串作為響應(yīng)報(bào)文,返回給服務(wù)器,讓服務(wù)器解析它,返回的文件類型是html。
如下大家可以看到,瀏覽器接受到了這個(gè)簡單的HTTP服務(wù)器發(fā)送過來的回應(yīng),并成功解析。
總結(jié)
以上是生活随笔為你收集整理的3-4:一个简单的HTTP服务器的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python Numpy 数组的初始化和
- 下一篇: SQL Server 2008 允许远程