【问题标题】:Bind a QTcpSocket to a specific port将 QTcpSocket 绑定到特定端口
【发布时间】:2016-01-17 02:06:48
【问题描述】:

我通过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();
}

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

【问题讨论】:

    标签: port qtcpsocket


    【解决方案1】:

    我将您的代码改写为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 很可能会解决这个问题。

    【讨论】:

      猜你喜欢
      • 2020-12-28
      • 1970-01-01
      • 1970-01-01
      • 2013-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-19
      • 1970-01-01
      相关资源
      最近更新 更多