在我的程序中,我想为我的TCP服务器设置客户端的限制。
目前,我的传入连接代码为:
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);
}
现在,我想将客户端数量限制为例如100个活动连接总数。我是否必须以某种特殊的方式处理它,或者只是使用简单的if(clients.count() < 100)
语句将其忽略?
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);
}
}
这样可以行吗?未处理的连接是否处于活动状态(已连接到服务器),但未在我的clients
词典中列出?
您可以使用QTcpServer::setMaxPendingConnections ( int numConnections )
。它设置到QTcpServer的最大传入连接数。
从Qt文档中:
无效的QTcpServer :: setMaxPendingConnections(int numConnections)
将待处理的接受连接的最大数量设置为numConnections。在调用nextPendingConnection()之前,QTcpServer最多接受numConnections个传入连接。默认情况下,该限制为30个挂起的连接。
服务器达到其最大未决连接数后,客户端仍可能能够连接(即QTcpSocket仍可以发出connectd()信号)。QTcpServer将停止接受新连接,但是操作系统仍可以将它们保持在队列中。
因此,如果连接数超过numConnections,则服务器将停止接受新连接,但OS可能会将它们排队。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句