将QTcpSocket绑定到特定端口 [英] Bind a QTcpSocket to a specific port

查看:1389
本文介绍了将QTcpSocket绑定到特定端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过QTcpSocket连接到QTcpServer.我可以在服务器端指定侦听端口,但是客户端会为其连接选择一个随机端口.我尝试使用方法QAbstractSocket::bind,但这没什么区别.

I am connecting through a QTcpSocket to a QTcpServer. I can specify the listening port on the Server side, but the client chooses a random port for its connection. I have tried to use the method QAbstractSocket::bind but that made no difference.

这是我的代码:

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

有人知道我想念什么吗?

Does anyone know what I'm missing?

推荐答案

我将您的代码重新编写为 MCVE :

I reformulated your code into a 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?

Why does connectToHost reset the local port to 0?

这似乎是Qt中的错误.在版本5.2.1中,QAbstractSocket::connectToHost包含

This appears to be a bug in Qt. In version 5.2.1, QAbstractSocket::connectToHost contains

d->state = UnconnectedState;
/* ... */
d->localPort = 0;
d->peerPort = 0;

在5.5版中,该名称已更改为

In version 5.5, this has changed to

if (d->state != BoundState) {
    d->state = UnconnectedState;
    d->localPort = 0;
    d->localAddress.clear();
}

因此升级Qt可能会解决该问题.

So it's likely that upgrading your Qt will fix the issue.

这篇关于将QTcpSocket绑定到特定端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆