我是Qt的初学者。我想用QUdpSocket写一个没有GUI的服务器应用程序。我已经写了客户端GUI应用程序和服务器GUI应用程序。他们工作得很好。但是没有GUI的服务器不能很好地工作.
我尝试使用 while(true) 循环让应用程序运行,因为我认为在代码“return a.exec()”之后应用程序将停止。但是我的服务器应用程序不工作。
这是我的代码: 带有 GUI 的客户端:
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
socket=new QUdpSocket(this);
//click pushbutton send message to server
connect(this->ui->pushButton,SIGNAL(clicked()),this,SLOT(send()));
}
Widget::~Widget()
{
delete ui;
}
//send message
void Widget::send()
{
QByteArray msg="client2:hello world";
socket->writeDatagram(msg.data(),msg.size(),QHostAddress::LocalHost,6666);
}
客户端应用程序和带有 GUI 应用程序的服务器可以正常工作。但是当我尝试制作没有 GUI 的服务器应用程序时,我发现服务器无法从客户端获取消息。 这是我没有 GUI 的 server.cpp:
#include "server.h"
Server::Server(QObject *parent) : QObject(parent)
{
socket=new QUdpSocket(this);
array=new QByteArray();
socket->bind(QHostAddress::LocalHost,6666,QAbstractSocket::DontShareAddress);
socket->open(QIODevice::ReadWrite); //without this line, the app will show:
//'QIOBevice::read(QUdpSocket):device not open',but it still can get the message from client.
connect(socket,SIGNAL(readyRead()),this,SLOT(printMsg()));
}
void Server::printMsg()
{
if(socket->hasPendingDatagrams()) //I forgot this line before.
{
array->resize(socket->pendingDatagramSize());
socket->readDatagram(array->data(),array->size());
socket->readAll();
qDebug()<<"yesyesyes";
}
}
我试了很多次,我认为问题出在我的 main.cpp 中:
#include <QCoreApplication>
#include "server.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Server s;
return a.exec();//after a.exec(),the app is still working!!!
}
在GUI应用程序中,如果我不关闭窗口,服务器应用程序将一直运行,并且我可以理解SIGNAL和SLOT。但是在控制台应用程序中,应用程序似乎结束得很快并且不能从客户端获取消息(无法显示消息)。
最佳答案
您的 main 中不应该有 while(true)
,否则,您实际上只是在卡住您的线程和 Qt 应用程序。这正是 app.exec();
的用途,它会在您的应用程序关闭时返回(更多详情 here )
如果您的应用程序(有或没有 GUI)在调用 app.exec()
后关闭,这是由于以下原因之一:
- 您正在手动关闭它,例如使用
qApp->quit();
- 您正在强制退出,例如使用
exit(1);
- fatal error 或异常会提前结束您的应用程序
关于c++ - 使用 QtUdpSocket 的简单通信 c/s 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55312628/