port - 将 QTcpSocket 绑定(bind)到特定端口

标签 port qtcpsocket

我通过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/

相关文章:

c++ - 不使用 readyRead() 信号从 QTcpSocket 读取

c++ - QThread中的QTcpSocket将commitTransaction但是当调用Write时 "Cannot create children for a parent that is in a different thread."

qt - 如何正确确定 QTCPSocket 中已到达输入结束?

qt4 - 如何找到Qt的版本?

c - 使用套接字的事件服务(端口)

interface - UML2 : ports and interfaces in component diagrams

ubuntu - 谁能告诉我tomcat 9中server.xml中的AUTOBIND在哪里,如附件答案中所述

port - 如何创建虚拟 MIDI 设备

c++ - QTcpSocket 无法绑定(bind)到正确的 IP

java - JT400 - JDBC 连接被 IBMi 机器拒绝,但在 Windows 机器上工作