我通过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 可能会解决该问题。
关于port - 将 QTcpSocket 绑定(bind)到特定端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33202353/