代码地址:https://github.com/xunshuidezhu/owl

owl是本人开发的一个基于reactor架构的网络库,包含了reactor模型,日志库,协程库,http模块,计时器,采用epoll LT模式,配合协程的使用,可以轻松实现异步网络io,而不必采用非阻塞io+epoll的多线程并发模型.

网络库的核心模型为reactor模式,主要有demultiplexer也就是事件分发者,reactor响应器,eventhandler事件处理程序,handles句柄集组成,其中handles其实是一个<handle, eventhandler>类型的map,也就是句柄对应相应的事件处理程序,通过find(handle)即可找到对应的注册在句柄上的时间处理程序.

事件分发代码:

具体通过epoll完成事件的分发通知

class EventDemultiplexer {
public:
    virtual ~EventDemultiplexer() {}

    virtual int waitEvent(std::map<handle_t, EventHandler*>*, int timeout, HeapTimerContainer*) = 0;

    virtual exit_t addEvent(handle_t handle, event_t event) = 0;

    virtual exit_t delEvent(handle_t) = 0;

    EventDemultiplexer(){};
};

class EpollEventDemultiplexer : public EventDemultiplexer {
public:
    EpollEventDemultiplexer();

    virtual int waitEvent(std::map<handle_t, EventHandler*>*, int timeout, HeapTimerContainer*) override;

    virtual exit_t addEvent(handle_t handle, event_t event_t) override;

    virtual exit_t delEvent(handle_t) override;

    virtual ~EpollEventDemultiplexer() override;

private:
    int _epoll_fd;

    int _fd_num;

    static int _epoll_size;
};

事件处理程序接口:

客端继承接口完成相应的read,write,error事件程序即可

class EventHandler {
public:
    virtual handle_t getHandle() const = 0;

    virtual void handleRead() = 0;

    virtual void handleWrite() = 0;

    virtual void handleError() = 0;

public:
    EventHandler(){};

    virtual ~EventHandler(){};
};

响应器程序:
具体实现在Impl中,包含了句柄集,事件处理程序,时间分发器,主要成员函数为注册事件,移除事件,处理事件,注册定时任务,定时器采用epoll_wait进行定时,gettimeofday进行计时,计时器容器采用小根堆,内含一个tick心跳函数,对应超时任务会触发回调函数.

class Reactor {
public:
    class ReactorImpl;

private:
    ReactorImpl* _reactorImpl;

public:
    explicit Reactor();

    ~Reactor();

    int registerHandler(EventHandler* handler, event_t event);

    int removeHandler(EventHandler* handler);

    void handlerEvent();

    int registerTimerTask(HeapTimer* timer);

private:
    Reactor(const Reactor&) {} // 禁止拷贝

    Reactor& operator=(const Reactor&) {} // 禁止赋值
};