我正在尝试创建一个应该连接到 C 服务器的客户端。我必须使用 TCP。我已经有一个功能齐全的服务器,但我无法连接我的客户端。我不想向服务器发送任何数据(此时)。我只想建立连接并打开一个新对话框。
这是 Void Login::on_pushButton_clicked() 插槽中的代码。//pushButon 是我的登录按钮
pSocket = new QTcpSocket (this);
connect (pSocket, SIGNAL(readyRead()), SLOT(waitNextStep()));
pSocket->connectToHost(ui->lineEdit->text(), ui->lineEdit_2->text().toInt());
if(pSocket->waitForConnected())
{
Menu mMenu;
mMenu.setModal(true);
mMenu.exec();
}
else
{
QMessageBox::critical(this,tr("Error"),tr("Error at Connect"));
}
我已经定义了 Menu 类,并且我知道它的功能,因为我在没有连接部分的情况下对其进行了测试。来自 lineEdits 的 IP 获取部分也可以使用。 pSocket 在登录类中声明为私有(private)成员 (QTcpSocket *pSocket;)。
不幸的是,我是 QT 的新手,我真的不知道“waitNextStep()”函数应该包含什么。我刚刚做了 return 1;我不确定连接函数中的 SLOT,因为我在许多示例中注意到那里有不同的函数。
如果我运行该程序,我不会收到任何错误,并且程序执行得很好。但是当我点击登录按钮时,对话框会卡住约 15 秒 - 它没有响应。之后,我收到“连接时出错”消息。任何帮助都感激不尽。
最佳答案
Unfortunatelly I'm new to QT and I don't really know what the 'waitNextStep()' function should containt. I just did a return 1; I am unsure about the SLOT in the connect function since I noticed in many examples that there were different functions there.
这在很大程度上取决于您的用例,但这通常是传入数据的处理程序,无论您希望如何处理它,可能包括您暂时将其存储在成员变量中。
If I run the program I get no errors and the program executes just fine. But when I hit the login button, the dialog box freezes for ~15 seconds - it's unresponsive. After that, I get the 'Error at connect' message. Any help will be much appreciated.
因为if(pSocket->waitForConnected())
是异步Qt操作的阻塞(即同步)用法。我建议改为按照 documentation 连接到已连接的信号:
void QAbstractSocket::connected() [signal]
This signal is emitted after connectToHost() has been called and a connection has been successfully established.
Note: On some operating systems the connected() signal may be directly emitted from the connectToHost() call for connections to the localhost.
关于c++ - Qt客户端——连接C服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21067451/