feat: max clients connected limit in TcpServer
This commit is contained in:
@@ -304,6 +304,7 @@ class SocketTcpServer : public TcpServer {
|
||||
bool open = true;
|
||||
std::unique_ptr<std::thread> thread = nullptr;
|
||||
int port;
|
||||
int maxConnected = -1;
|
||||
public:
|
||||
SocketTcpServer(u64id_t id, Network* network, SOCKET descriptor, int port)
|
||||
: id(id), network(network), descriptor(descriptor), port(port) {}
|
||||
@@ -312,6 +313,22 @@ public:
|
||||
closeSocket();
|
||||
}
|
||||
|
||||
void setMaxClientsConnected(int count) override {
|
||||
maxConnected = count;
|
||||
}
|
||||
|
||||
void update() override {
|
||||
std::vector<u64id_t> clients;
|
||||
for (u64id_t cid : this->clients) {
|
||||
if (auto client = network->getConnection(cid, true)) {
|
||||
if (client->getState() != ConnectionState::CLOSED) {
|
||||
clients.emplace_back(cid);
|
||||
}
|
||||
}
|
||||
}
|
||||
std::swap(clients, this->clients);
|
||||
}
|
||||
|
||||
void startListen(ConnectCallback handler) override {
|
||||
thread = std::make_unique<std::thread>([this, handler]() {
|
||||
while (open) {
|
||||
@@ -328,6 +345,11 @@ public:
|
||||
close();
|
||||
break;
|
||||
}
|
||||
if (maxConnected >= 0 && clients.size() >= maxConnected) {
|
||||
logger.info() << "refused connection attempt from " << to_string(address);
|
||||
closesocket(clientDescriptor);
|
||||
continue;
|
||||
}
|
||||
logger.info() << "client connected: " << to_string(address);
|
||||
auto socket = std::make_shared<SocketTcpConnection>(
|
||||
clientDescriptor, address
|
||||
@@ -575,6 +597,8 @@ public:
|
||||
SocketUdpServer::close();
|
||||
}
|
||||
|
||||
void update() override {}
|
||||
|
||||
void startListen(ServerDatagramCallback handler) override {
|
||||
callback = std::move(handler);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user