2015-10-18 327 views
0

我通過QTcpSocket連接到QTcpServer。我可以在服務器端指定監聽端口,但客戶端爲其連接選擇一個隨機端口。我試圖使用方法QAbstractSocket::bind但這沒有什麼區別。將QTcpSocket綁定到特定端口

這裏是我的代碼:

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

有誰知道我錯過了什麼?

回答

2

我重新代碼爲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將解決這個問題。