a8/a8/tcplistener.h
2023-09-28 01:08:51 +00:00

70 lines
1.8 KiB
C++

#pragma once
#include <atomic>
namespace a8
{
enum TCPLISTENER_E
{
TE_CREATE_ERR,
TE_SETSOCKOPT_ERR,
TE_BIND_ERR,
TE_LISTEN_ERR,
};
struct TcpListenerImpl;
class TcpSession;
class TcpListener
{
public:
std::function<void (const char*, int, bool&)> on_client_connect;
std::function<void (a8::TcpListener*, a8::TCPLISTENER_E, int)> on_error;
std::string bind_address;
unsigned short bind_port = 0;
std::atomic<long long> send_node_num = {0};
std::atomic<long long> sent_node_num = {0};
std::atomic<long long> sent_bytes_num = {0};
std::atomic<long long> recv_bytes_num = {0};
public:
TcpListener(unsigned short max_client_cnt=0xEFFF);
virtual ~TcpListener();
void Open();
void Close();
bool IsActive();
template <typename T>
void RegisterSessionClass()
{
on_create_client_socket_ =
[] (a8::TcpSession** p)
{
*p = new T;
};
}
bool SendClientMsg(unsigned short sockhandle, const char *buff, int buffLen);
void BroadcastMsg(const char* buff, int bufflen);
void ForceCloseClient(unsigned short sockhandle);
void MarkClient(unsigned short sockhandle, bool is_active);
int GetClientSocketCount();
int GetPoolSocketCount();
private:
void LockClients();
void FreeClientWithNoLock(a8::TcpSession *session);
void UnLockClients();
a8::TcpSession* GetClientSession(unsigned short handle);
private:
std::function<void (a8::TcpSession**)> on_create_client_socket_;
a8::TcpListenerImpl* impl_ = nullptr;
friend class TcpSession;
friend class a8::TcpListenerImpl;
};
}