要实现http服务器,首先得了解http协议。同样,要用socket实现服务器,那就得熟悉socket了。
最近的项目中要实现一个类似http服务器的功能,项目是Windows平台下。
心血来潮,顺便在Linux下也实现了一个简单server。目前,仅支持GET、HEAD和POST方法,待有空时继续完善。
使用socket,采用多线程处理每个客户端的连接请求,未处理客户端connection(keep-alive or not)方式。select epoll 方式在本这边并无方便或高效之处,所以未使用该方式。
具体代码:https://github.com/donglinshengan/httpServer 供有需要者参考
Linux下使用socket与Windows下大体相同,部分接口不同,socket初始化也不同,不在此详述了。
下面贴出主要代码:
#pragma once
/**********************************************************/
/* HttpHandler: handle the client http request */
/**********************************************************/
class HttpHandler
{
public:
HttpHandler(int sockConn);
~HttpHandler();
enum tagReqMethod {Method_NULL, Method_GET, Method_HEAD,
Method_POST, Method_OPTION,Method_PUT, Method_DELETE,
Method_CONNECT, Method_TRACE};
public:
int ClientConnHandler(); // the handler to the connections
protected:
/* handle the request */
int RequestHandle(tagReqMethod method, const char* pPath);
/* send the response content to the client */
int SendResponseContent(const char* pPath, bool bOnlyHeader=false);
/* handle the error request */
int SendFailureResponse(int nErrCode, const char* pPath);
/* send the http header if the request should be handled correctly */
int SendResponseHeader(int nContentLength);
/* get the request path */
tagReqMethod GetRequestPath(const char* pDataRequest, char* pBuf, int nSize);
/* get the http header sent by the client */
char* GetHeaderContent(const char* pData, const char* pName, char* pBuf, int nSize);
private:
int m_sockConn; // socket the client request connected
};
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <errno.h>
#include ".