2015-10-18 320 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将解决这个问题。