在瞭解HTTP協議在應用層的一些通信規則後,我們可以開始寫一個簡單的http server,加深對socket的理解。
爲了簡單起見,這裏不對請求的方法等進行判定,默認爲GET;也不請求特定資源。
(一)TCP服務器
簡單起見,這裏用簡單的單線程迭代服務器,即在一個while循環裏面不斷接收請求處理請求。
套接字函數
這裏的所有的套接字函數都是使用unp中的包裹函數:
int Socket(int ,int,int);
void Bind(int ,const struct sockaddr*sa,socklen_t salen);
void Listen(int ,int);
int Accept(int,struct sockaddr*,socklen_t*);
int //創建套接字
Socket(int family , int type,int protocol)
{
int n;
if ( (n = socket(family, type, protocol)) < 0)
{
printf("socket error\r\n");
return -1;
}
return(n);
}
void//綁定套接字
Bind(int fd, const struct sockaddr *sa, socklen_t salen)
{
if (bind(fd, sa, salen) < 0)
{
printf("bind error\r\n");
exit(-1);
}
}
void//監聽套接字
Listen(int fd, int backlog)
{
char *ptr;
/*4can override 2nd argument with environment variable */
if ( (ptr = getenv("LISTENQ")) != NULL)
backlog = atoi(ptr);
if (listen(fd, backlog) < 0)
{
printf("listen error\r\n");
return ;
}
}
int//接收連接
Accept(int fd, struct sockaddr *sa, socklen_t *salenptr)
{
int n;
again:
if ( (n = accept(fd, sa, salenptr)) < 0) {
#ifdef EPROTO
if (errno == EPROTO || errno == ECONNABORTED)
#else
if (errno == ECONNABORTED)
#endif
goto again;
else
{
printf("accept error\r\n");
return -1;
}
}
return(n);
}
(二)解析HTTP請求
int getRequest(int socket)
{
int msgLen=0;
char buffer[BUFFER_SIZE];
memset (buffer,'\0', BUFFER_SIZE);
if ((msgLen = recv(socket, buffer, BUFFER_SIZE, 0)) == -1)//接收TCP流
{
printf("Error handling incoming request");
return -1;
}
//以下僅僅在GDB中調試驗證
stringstream ss;
ss<<buffer;//請求的所有字符內容
string method;//請求方法
ss>>method;
string uri;//請求uri
ss>>uri;
string version;//http協議版本
ss>>version;
//...
}
由於在本實現中,不對請求方法做區分,因此這裏不對請求內容再做判斷,僅僅通過GDB調試解析出的內容是否正確。
(三)構造HTTP響應
構造一個HTTP響應就要按照要求構造響應行,響應頭部字段和值,響應的實體(這裏爲簡單的html文本)。
string statusCode("200 OK");//響應狀態碼
string contentType("text/html");//content-type字段值
string content("<html><head><title>my simple httpserver</title></head><h1>hello zx world</h1></body></html>");//響應實體
string contentSize(std::to_string(content.size()));//響應實體大小
string head("\r\nHTTP/1.1 ");//版本
string ContentType("\r\nContent-Type: ");//頭部字段
string ServerHead("\r\nServer: localhost");//頭部字段和值
string ContentLength("\r\nContent-Length: ");//頭部字段
string Date("\r\nDate: ");//頭部字段
string Newline("\r\n");
time_t rawtime;
time(&rawtime);//獲取時間
string message;
//按照http響應的順序和要求構造響應頭部
message+=head;
message+=statusCode;
message+=ContentType;
message+=contentType;
message+=ServerHead;
message+=ContentLength;
message+=contentSize;
message+=Date;
message+=(string)ctime(&rawtime);
message+=Newline;
int messageLength=message.size();
int n;
n=send(socket,message.c_str(),messageLength,0);//發送響應頭
n=send(socket,content.c_str(),content.size(),0);//發送響應實體
(四)完整代碼
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <netinet/in.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <pthread.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
#define BUFFER_SIZE 512
int Socket(int ,int,int);
void Bind(int ,const struct sockaddr*sa,socklen_t salen);
void Listen(int ,int);
int Accept(int,struct sockaddr*,socklen_t*);
void handleAccept(int);
void handleHttp(int);
int getRequest(int);
int main(int argc,char **argv)
{
const int port = 1024;//listen port
int listenfd=Socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_in serverAddr;
serverAddr.sin_family=AF_INET;
serverAddr.sin_addr.s_addr=INADDR_ANY;
serverAddr.sin_port=htons(port);
Bind(listenfd,(struct sockaddr*)&serverAddr,sizeof(serverAddr));
Listen(listenfd,5);
while(true)
{
handleAccept(listenfd);
}
}
int Socket(int family , int type,int protocol)
{
int n;
if ( (n = socket(family, type, protocol)) < 0)
{
printf("socket error\r\n");
return -1;
}
return(n);
}
void
Bind(int fd, const struct sockaddr *sa, socklen_t salen)
{
if (bind(fd, sa, salen) < 0)
{
printf("bind error\r\n");
exit(-1);
}
}
void
Listen(int fd, int backlog)
{
char *ptr;
/*4can override 2nd argument with environment variable */
if ( (ptr = getenv("LISTENQ")) != NULL)
backlog = atoi(ptr);
if (listen(fd, backlog) < 0)
{
printf("listen error\r\n");
return ;
}
}
int
Accept(int fd, struct sockaddr *sa, socklen_t *salenptr)
{
int n;
again:
if ( (n = accept(fd, sa, salenptr)) < 0) {
#ifdef EPROTO
if (errno == EPROTO || errno == ECONNABORTED)
#else
if (errno == ECONNABORTED)
#endif
goto again;
else
{
printf("accept error\r\n");
return -1;
}
}
return(n);
}
void handleAccept(int listenfd)
{
sockaddr_in clientAddr;
socklen_t clientLen=sizeof(clientAddr);
int connfd=Accept(listenfd,(sockaddr *)&clientAddr,&clientLen);
handleHttp(connfd);
close(connfd);
}
void handleHttp(int connfd)
{
if(getRequest(connfd)<0)
{
perror("http request get error");
exit(-1);
}
}
int getRequest(int socket)
{
int msgLen=0;
char buffer[BUFFER_SIZE];
memset (buffer,'\0', BUFFER_SIZE);
if ((msgLen = recv(socket, buffer, BUFFER_SIZE, 0)) == -1)
{
printf("Error handling incoming request");
return -1;
}
stringstream ss;
ss<<buffer;
string method;
ss>>method;
string uri;
ss>>uri;
string version;
ss>>version;
//
string statusCode("200 OK");
string contentType("text/html");
string content("<html><head><title>my simple httpserver</title></head><h1>hello zx world</h1></body></html>");
string contentSize(std::to_string(content.size()));
string head("\r\nHTTP/1.1 ");
string ContentType("\r\nContent-Type: ");
string ServerHead("\r\nServer: localhost");
string ContentLength("\r\nContent-Length: ");
string Date("\r\nDate: ");
string Newline("\r\n");
time_t rawtime;
time(&rawtime);
string message;
message+=head;
message+=statusCode;
message+=ContentType;
message+=contentType;
message+=ServerHead;
message+=ContentLength;
message+=contentSize;
message+=Date;
message+=(string)ctime(&rawtime);
message+=Newline;
int messageLength=message.size();
int n;
n=send(socket,message.c_str(),messageLength,0);
n=send(socket,content.c_str(),content.size(),0);
return n;
}
比較簡陋的實現。
(五)測試
編譯運行,用curl測試
curl -v localhost:1024