在了解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