Doro
Doro

Reputation: 785

Refusing incoming connections to TCP Server

In my program I'd like to set the limit of clients for my TCP server.

Currently my code for incoming connections is:

void TCPServer::incomingConnection(int handle)
{
    QPointer<TCPClient> client = new TCPClient(this);
    client->SetSocket(handle);

    clients[handle] = client;

    QObject::connect(client, SIGNAL(MessageRecieved(int,QString)), this, SLOT(MessageRecieved(int,QString)));
    QObject::connect(client, SIGNAL(ClientDisconnected(int)), this, SLOT(ClientDisconnected(int)));

    emit ClientConnected(handle);
}

Now I'd like to limit the number of clients to for example 100 total active connections. Do I have to handle it in some special way or just ignore it by using simple if(clients.count() < 100) statement?

void TCPServer::incomingConnection(int handle)
{
    if(clients.count() < 100)
    {
        QPointer<TCPClient> client = new TCPClient(this);
        client->SetSocket(handle);

        clients[handle] = client;

        QObject::connect(client, SIGNAL(MessageRecieved(int,QString)), this, SLOT(MessageRecieved(int,QString)));
        QObject::connect(client, SIGNAL(ClientDisconnected(int)), this, SLOT(ClientDisconnected(int)));

        emit ClientConnected(handle);
    }
}

Is it ok to do it in that way? Do unhandled connections are active (connected to server) but just not listed in my clients dictionary?

Upvotes: 5

Views: 1947

Answers (1)

Nejat
Nejat

Reputation: 32635

You can use QTcpServer::setMaxPendingConnections ( int numConnections ). It sets the maximum number of incoming connections to QTcpServer.

From the Qt documentation :

void QTcpServer::setMaxPendingConnections(int numConnections)

Sets the maximum number of pending accepted connections to numConnections. QTcpServer will accept no more than numConnections incoming connections before nextPendingConnection() is called. By default, the limit is 30 pending connections.

Clients may still able to connect after the server has reached its maximum number of pending connections (i.e., QTcpSocket can still emit the connected() signal). QTcpServer will stop accepting the new connections, but the operating system may still keep them in queue.

So if the number of connections grows past numConnections the server will stop accepting new connections but the OS may queue them.

Upvotes: 3

Related Questions