基于socket实现http服务器

要实现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 ".
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值