【问题标题】:QTcpServer::hadPendingConnections() returns false upon new connectionQTcpServer::hadPendingConnections() 在新连接时返回 false
【发布时间】:2016-07-08 08:42:03
【问题描述】:

我正在开发一些服务器应用程序,该框架是QTcpServer 的子类,名为UeTcpServer。服务器应用程序正常启动,当我在ueSlotTcpServerNewConnection() 中放置断点时,它通过连接到UeTcpServernewConnectionSignal

connect(this->ueTcpServer(),
        SIGNAL(newConnection()),
        this,
        SLOT(ueSlotTcpServerNewConnection()));

然后使用Linux terminal 连接到服务器应用程序,断点在ueSlotTcpServerNewConnection() 插槽内激活:

void UeMainWindow::ueSlotTcpServerNewConnection()
{
    if(this->ueTcpServer()->hasPendingConnections())
    {
        QTcpSocket* incomingSocket=this->ueTcpServer()->nextPendingConnection();

        this->ueSlotAddEventInfoLog(0,
                                    tr("New incoming connection from host")
                                    .append(" ")
                                    //.append(this->ueTcpServer()->nextPendingConnection()->peerAddress().toString())
                                    .append(incomingSocket->peerName())
                                    .append(" ")
                                    .append(tr("with IP address"))
                                    .append(" ")
                                    .append(incomingSocket->peerAddress().toString())
                                    .append(" ")
                                    .append(tr("using port"))
                                    .append(" ")
                                    //.append(this->ueTcpServer()->nextPendingConnection()->peerPort()));
                                    .append(QString::number(incomingSocket->peerPort())));
    }   // if
}   // ueSlotTcpServerNewConnection

但是,this->ueTcpServer()->hasPendingConnection() 返回false。为什么?

【问题讨论】:

  • 查看了我自己对QTcpServer 的使用情况,我倾向于使用while (QTcpSocket *conn = server->nextPendingConnection()) { 并且从未遇到任何问题。所以我的问题是......当hasPendingConnections 返回 false 时,nextPendingConnection 是否返回 NULL/nullptr - 或者它实际上是否返回有效连接?
  • @G.M.如果我删除/评论if(this->ueTcpServer()->hasPendingConnections()),我会得到NULL 指向QTcpSocket 的指针。
  • 您是否在应用程序的 QTcpServer 子类中重新实现了incomingConnection。如果是这样,也许你忘记调用 addPendingConnection。
  • 就是这样!我忘了从incomingConnection(qintptr socketDescriptor) 打电话给addPendingConnection(QTcpSocket* socket)。现在可以了!

标签: qt qtcpserver


【解决方案1】:

我忘了从incomingConnection(qintptr socketDescriptor) 打电话给addPendingConnection(QTcpSocket *socket,正如docs 中所述:

void UeTcpServer::incomingConnection(qintptr socketDescriptor)
{  
    QTcpSocket* newSocket=new QTcpSocket(this);

    newSocket->setSocketDescriptor(socketDescriptor);

    this->addPendingConnection(newSocket);
}   // incomingConnection

现在可以使用了。

【讨论】:

  • 如果这就是你想做的所有事情,你不需要覆盖incomingConnection,因为这正是base implementation所做的。
  • 如果使用函数参数,为什么要Q_UNUSED...?
猜你喜欢
  • 1970-01-01
  • 2018-09-09
  • 1970-01-01
  • 1970-01-01
  • 2013-07-13
  • 1970-01-01
  • 2018-03-09
  • 2014-10-05
  • 2013-11-19
相关资源
最近更新 更多