gpt4 book ai didi

qt - 拒绝到 TCP 服务器的传入连接

转载 作者:可可西里 更新时间:2023-11-01 02:32:52 27 4
gpt4 key购买 nike

在我的程序中,我想为我的 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 文档:

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.

因此,如果连接数超过 numConnections,服务器将停止接受新连接,但操作系统可能会将它们排队。

关于qt - 拒绝到 TCP 服务器的传入连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24219726/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com