将 QTcpSocket 绑定到特定端口

Bind a QTcpSocket to a specific port

我正在通过 QTcpSocket 连接到 QTcpServer。我可以在服务器端指定监听端口,但客户端会为其连接选择一个随机端口。我曾尝试使用 QAbstractSocket::bind 方法,但没有任何区别。

这是我的代码:

void ConnectionHandler::connectToServer() {
     this->socket->bind(QHostAddress::LocalHost, 2001);
     this->socket->connectToHost(this->ip, this->port);

     if (!this->socket->waitForConnected()) {
           this->socket->close();
           this->errorMsg = this->socket->errorString();
      }

     qDebug() << this->socket->localPort();
}

有人知道我错过了什么吗?

我将您的代码重新表述为 MCVE

#include <QDebug>
#include <QHostAddress>
#include <QTcpSocket>

#include <memory>

int main()
{
    std::unique_ptr<QTcpSocket> socket(new QTcpSocket);

    socket->bind(QHostAddress::LocalHost, 2001);
    qDebug() << socket->localPort(); // prints 2001

    socket->connectToHost(QHostAddress::LocalHost, 25);
    qDebug() << socket->localPort(); // prints 0
}

为什么connectToHost将本地端口重置为0?

这似乎是 Qt 中的错误。在 5.2.1 版本中,QAbstractSocket::connectToHost 包含

d->state = UnconnectedState;
/* ... */
d->localPort = 0;
d->peerPort = 0;

在 5.5 版本中,这已更改为

if (d->state != BoundState) {
    d->state = UnconnectedState;
    d->localPort = 0;
    d->localAddress.clear();
}

所以升级您的 Qt 可能会解决这个问题。