我正在通过一个连接QTcpSocket
to a 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 /help/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 可能会解决该问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)