gpt4 book ai didi

qt - Simple Qt code for network 简单网络连接

转载 作者:可可西里 更新时间:2023-11-01 02:46:21 25 4
gpt4 key购买 nike

我对使用 QtNetwork 连接计算机完全陌生。

现在我只想看到连接尝试。因此,我创建了一个 GUI 应用程序,并在 mainwindow.cpp 上将这两个函数编写为两个按钮的插槽:

void MainWindow::on_pbTalk_clicked(){
QString IP = ui->leIP->text();
ui->pteLog->appendPlainText("Now Talking to IP: " + IP);
talker = new Talker();
talker->connectToHost(IP,25000);
}

void MainWindow::on_pbListen_clicked(){
ui->pteLog->appendPlainText("Now listening on any port, I think");
listener = new Listener(this);
if (!connect(listener, SIGNAL(newConnection()), this, SLOT(on_newConnections()))){
ui->pteLog->appendPlainText("The connection of slot and signal failed!");
}
}

现在 Talker 本质上是一个 QTcpSocket,还没有重新实现任何东西。

Listener 是一个 QTcpServer,具有以下代码 con Listener.cpp:

Listener::Listener(QObject *parent) :
QTcpServer(parent)
{

qDebug() << "Listening on any port";
listen(QHostAddress::Any);

}

void Listener::incomingConnection(int socketDescriptor){
qDebug() << "New connection: " << socketDescriptor;
}

所以我运行了同一个程序的两个实例。一个在我的机器里。我运行该程序并按下“收听”按钮(IP 10.255.255.101)。

第二个实例在虚拟机 (IP 10.255.255.215) 中运行,我在其中运行程序并按下通话按钮。据我所知,这应该尝试在端口 25000 打开到 IP(10.255.255.101)的连接,我应该在控制台中收到“新连接”消息。但是没有出现这样的消息。由于这不起作用,我不会继续前进。

任何人都可以告诉我我可能做错了什么吗?

最佳答案

检查 QTcpServer::listen 的文档- 它说:

Tells the server to listen for incoming connections on address address and port port. If port is 0, a port is chosen automatically. If address is QHostAddress::Any, the server will listen on all network interfaces.

QHostAddress::Any 表示您正在监听所有网络接口(interface),而不是端口。 (例如,如果您只想拥有一个本地服务器,您可以使用 QHostAddress::LocalHost - 检查 QHostAddress::SpecialAddress 以获得更多类似信息。

如果你想手动设置端口,你必须调用:

listen(QHostAddress::Any, 25000);

如果没有,你可以通过调用获取自动选择的端口

quint16 port = serverPort();

关于qt - Simple Qt code for network 简单网络连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35704775/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com