tinyrpc/includes/net/fd_event.hpp

72 lines
1.8 KiB
C++
Raw Permalink Normal View History

2024-12-20 21:17:21 +08:00
#pragma once
#include "reactor.hpp"
#include <functional>
2025-01-14 15:27:15 +08:00
#include <mutex>
2024-12-20 21:17:21 +08:00
#include <sys/epoll.h>
2025-01-14 15:27:15 +08:00
#include <unordered_map>
2024-12-25 19:40:27 +08:00
2024-12-20 21:17:21 +08:00
namespace tinyrpc {
enum class IOEvent{
READ = EPOLLIN,
WRITE = EPOLLOUT,
// ERROR = EPOLLERR
};
class FdEvent {
2025-01-14 15:27:15 +08:00
friend class FdEventPool;
2024-12-20 21:17:21 +08:00
public:
2025-01-14 15:27:15 +08:00
void clearListenEvent() {
m_listen_events = 0;
}
2024-12-20 21:17:21 +08:00
int getFd() const{return m_fd;}
int getEvent() const { return m_listen_events;}
void setReadCallback(std::function<void()> read_callback) {
m_read_callback = read_callback;
}
void setWriteCallback(std::function<void()> write_callback) {
m_write_callback = write_callback;
}
bool setNonblock();
std::function<void()> getHandler(IOEvent event) const;
void addListenEvent(IOEvent event);
void delListenEvent(IOEvent event);
2025-01-16 14:41:46 +08:00
void reset();
protected:
2025-01-14 15:27:15 +08:00
FdEvent(int fd);
~FdEvent();
FdEvent() = default;
FdEvent(int fd, Reactor* reactor);
FdEvent(const FdEvent&) = delete;
protected:
2024-12-20 21:17:21 +08:00
int m_fd {-1};
2024-12-25 19:40:27 +08:00
Reactor::Task m_read_callback{m_default_callback};
Reactor::Task m_write_callback{m_default_callback};
2024-12-20 21:17:21 +08:00
// std::function<void()> m_error_callback{nullptr};
Reactor* m_reactor{nullptr}; // 这个fd 所属的 reactor
int m_listen_events {0}; // 这个fd 关心的事件
2024-12-25 19:40:27 +08:00
static Reactor::Task m_default_callback;
2024-12-20 21:17:21 +08:00
};
2025-01-14 15:27:15 +08:00
class FdEventPool{
public:
static FdEventPool* getInstance();
FdEvent* getFdEvent(int fd);
~FdEventPool();
private:
FdEventPool() = default;
private:
std::mutex m_mtx{};
std::unordered_map<int, FdEvent*> m_fdEvents{};
};
2024-12-20 21:17:21 +08:00
}