回调函数对象 (_connected_callback, _message_callback, _closed_callback, _event_callback)
class TcpServer {
private:
uint64_t _next_id;
int _port;
int _timeout;
bool _enable_inactive_release;
EventLoop _baseloop;
Acceptor _acceptor;
LoopThreadPool _pool;
std::unordered_map<uint64_t, PtrConnection> _conns;
private:
using ConnectedCallback = std::function<void(const PtrConnection&)>;
using MessageCallback = std::function<void(const PtrConnection&, Buffer*)>;
using ClosedCallback = std::function<void(const PtrConnection&)>;
using AnyEventCallback = std::function<void(const PtrConnection&)>;
using Functor = std::function<void()>;
ConnectedCallback _connected_callback;
MessageCallback _message_callback;
ClosedCallback _closed_callback;
AnyEventCallback _event_callback;
void NewConnection(int fd) {
_next_id++;
PtrConnection conn(new Connection(_pool.NextLoop(), _next_id, fd));
conn->SetMessageCallback(_message_callback);
conn->SetClosedCallback(_closed_callback);
conn->SetConnectedCallback(_connected_callback);
conn->SetAnyEventCallback(_event_callback);
conn->SetSrvClosedCallback(std::bind(&TcpServer::RemoveConnection, this, conn));
if (_enable_inactive_release) conn->EnableInactiveRelease(_timeout);
conn->Established();
_conns.insert(std::make_pair(_next_id, conn));
}
void RemoveConnectionInLoop(const PtrConnection& conn) {
uint64_t id = conn->Id();
auto it = _conns.find(id);
if (it != _conns.end()) {
_conns.erase(it);
}
}
void RemoveConnection(const PtrConnection& conn) {
_baseloop.RunInLoop(std::bind(&TcpServer::RemoveConnectionInLoop, this, conn));
}
void RunAfterInLoop(const Functor task, int delay) {
_next_id++;
_baseloop.TimerAdd(_next_id, delay, task);
}
public:
TcpServer(int port) : _port(port), _next_id(0), _enable_inactive_release(false), _acceptor(&_baseloop, port), _pool(&_baseloop) {
_acceptor.SetAcceptCallback(std::bind(&TcpServer::NewConnection, this, std::placeholders::_1));
_acceptor.Listen();
}
void SetThreadCount(int count) {
_pool.SetThreadCount(count);
}
void SetConnectedCallback(const ConnectedCallback& cb) {
_connected_callback = cb;
}
void SetMessageCallback(const MessageCallback& cb) {
_message_callback = cb;
}
void SetClosedCallback(const ClosedCallback& cb) {
_closed_callback = cb;
}
void SetAnyEventCallback(const AnyEventCallback& cb) {
_event_callback = cb;
}
void RunAfter(const Functor task, int delay) {
_baseloop.RunInLoop(std::bind(&TcpServer::RunAfterInLoop, this, task, delay));
}
void EnableInactiveRelease(int timeout) {
_timeout = timeout;
_enable_inactive_release = true;
}
void Start() {
_pool.Create();
_baseloop.Start();
}
};