2016-03-14 04:51:04 +08:00
|
|
|
#pragma once
|
|
|
|
|
2016-08-11 11:47:30 +08:00
|
|
|
#include "io/network/stream_reader.hpp"
|
2016-03-14 04:51:04 +08:00
|
|
|
|
|
|
|
namespace io
|
|
|
|
{
|
|
|
|
|
2016-08-02 05:14:09 +08:00
|
|
|
template <class Derived>
|
|
|
|
class Server : public EventListener<Derived>
|
2016-03-14 04:51:04 +08:00
|
|
|
{
|
|
|
|
public:
|
2016-09-08 19:10:20 +08:00
|
|
|
Server(Socket &&socket) : socket(std::forward<Socket>(socket)),
|
|
|
|
logger(logging::log->logger("io::Server"))
|
2016-03-14 04:51:04 +08:00
|
|
|
{
|
2016-08-02 05:14:09 +08:00
|
|
|
event.data.fd = this->socket;
|
2016-09-08 19:10:20 +08:00
|
|
|
|
|
|
|
// TODO: EPOLLET is hard to use -> figure out how should EPOLLET be used
|
|
|
|
// event.events = EPOLLIN | EPOLLET;
|
|
|
|
event.events = EPOLLIN;
|
2016-03-14 04:51:04 +08:00
|
|
|
|
2016-08-02 05:14:09 +08:00
|
|
|
this->listener.add(this->socket, &event);
|
|
|
|
}
|
2016-03-14 04:51:04 +08:00
|
|
|
|
2016-08-30 22:12:30 +08:00
|
|
|
void on_close_event(Epoll::Event &event) { ::close(event.data.fd); }
|
2016-03-14 04:51:04 +08:00
|
|
|
|
2016-08-30 22:12:30 +08:00
|
|
|
void on_error_event(Epoll::Event &event) { ::close(event.data.fd); }
|
2016-03-14 04:51:04 +08:00
|
|
|
|
2016-08-30 22:12:30 +08:00
|
|
|
void on_data_event(Epoll::Event &event)
|
2016-08-02 05:14:09 +08:00
|
|
|
{
|
2016-08-30 22:12:30 +08:00
|
|
|
if (UNLIKELY(socket != event.data.fd)) return;
|
2016-03-14 04:51:04 +08:00
|
|
|
|
2016-08-02 05:14:09 +08:00
|
|
|
this->derived().on_connect();
|
2016-03-14 04:51:04 +08:00
|
|
|
}
|
2016-08-02 05:14:09 +08:00
|
|
|
|
2016-08-30 22:12:30 +08:00
|
|
|
template <class... Args>
|
|
|
|
void on_exception_event(Epoll::Event &event, Args &&... args)
|
|
|
|
{
|
|
|
|
// TODO: Do something about it
|
2016-09-08 19:10:20 +08:00
|
|
|
logger.warn("epoll exception");
|
2016-08-30 22:12:30 +08:00
|
|
|
}
|
|
|
|
|
2016-08-02 05:14:09 +08:00
|
|
|
protected:
|
|
|
|
Epoll::Event event;
|
|
|
|
Socket socket;
|
2016-09-08 19:10:20 +08:00
|
|
|
Logger logger;
|
2016-03-14 04:51:04 +08:00
|
|
|
};
|
|
|
|
}
|