【发布时间】:2018-09-06 02:39:15
【问题描述】:
我在这里通常使用这种方法向自己发送 UDP 数据包:
How to receive proper UDP packet in QT?
我正在设置模式,以便在写入模式下,它每秒发送 UDP 数据包,而在读取模式下,它只接收数据包。为此,我设置了一个名为 readmode 的简单布尔变量,当 readmode = true 它在 = false 时进行读写。我将connect(socket, SIGNAL(readyRead()), this,SLOT(readyRead())); 和对send 函数的调用留在MainWindow 构造函数中,并将if 语句放在发送函数和readyRead() 函数本身中测试readMode 的状态以实际执行某些操作。
我的问题是,只有在打开程序写入窗口之前先以读取模式启动程序时,我才会收到数据包。如果我在打开 Read 程序之前开始发送数据包,我将一无所获。
为了澄清起见,我打开了这个程序的两个实例,我将一个设置为读取,另一个设置为写入,但是必须首先启动读取才能使其工作,但一旦状态发生更改,它就会停止工作。
我怎样才能让它一直阅读?
代码示例:
bool readMode = true; //Write mode = false, Read Mode = true
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
timer = new QTimer(this);
timer->start(1000);
ui->buttonBox->button(QDialogButtonBox::Ok)->setText("Read");
ui->buttonBox->button(QDialogButtonBox::Cancel)->setText("Write");
out_socket = new QUdpSocket(this);
out_socket->bind(60500);
in_socket = new QUdpSocket(this);
in_socket->bind(60510);
connect(timer, SIGNAL(timeout()),this,SLOT(UDP_test()));
connect(in_socket,SIGNAL(readyRead()),this,SLOT(readyRead()));
}
void MainWindow::UDP_test() //Write Mode
{
if (readMode == false) //Write Mode
{
QByteArray Data;
Data.append(fullResultString);
out_socket->writeDatagram(Data,QHostAddress("192.168.127.10"),60510);
}
void MainWindow::readyRead() //Read Mode
{
if (readMode == true) //Readmode
{
while(in_socket->hasPendingDatagrams())
{
QByteArray UDPBuffer;
UDPBuffer.resize(in_socket->pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
in_socket->readDatagram(UDPBuffer.data(),UDPBuffer.size(), &sender, &senderPort);
}
【问题讨论】:
-
boolean 变量应该设置/测试true/false,而不是1/0。尽管它可能只是一个坏主意和令人困惑的(你让读者认为这是int)。