我向系统发送命令并从中读取响应。我的机器是客户端,我成功地将数据包写入服务器,但是,我无法收到来自它的响应。我想知道为什么会发生这种情况,请查看我的代码:(服务器地址为 192.168.100.143,端口为 11000)
void UDP::UDPInit(int port)
{
socketPort = port;
udpsocket = new QUdpSocket(this);
}
void UDP::sendCommand(QByteArray data)
{
QHostAddress *host = new QHostAddress("192.168.100.143");
quint16 port = 11000;
if(udpsocket->writeDatagram(data.data(),QHostAddress(ip),socketPort)==-1)
emit clientLogMessage(QString("UDPCLIENT : Write problem !"));
else
udpsocket->flush();
while (!udpsocket->hasPendingDatagrams()) {
QByteArray datagram;
datagram.resize(udpsocket->pendingDatagramSize());
qDebug() << udpsocket->pendingDatagramSize();
udpsocket->readDatagram(datagram.data(), datagram.size(), host, &port);
emit dataReceived(datagram);
}
}
QUdpSocket 有一个信号 readyRead 每次有新数据包可用时都会发出,如果您在事件循环中,我建议您使用它
while 中的条件被否定,这意味着 udpsocket->pendingDatagramSize()
将在 while 循环中返回 -1,readDatagram
将丢弃数据包
固定代码:
void UDP::UDPInit(int port)
{
socketPort = port;
udpsocket = new QUdpSocket(this);
connect(udpsocket, SIGNAL(readyRead()), this, SLOT(readSocket()));
}
void UDP::sendCommand(QByteArray data)
{
QHostAddress *host = new QHostAddress("192.168.100.143");
quint16 port = 11000;
if(udpsocket->writeDatagram(data.data(),QHostAddress(ip),socketPort)==-1)
emit clientLogMessage(QString("UDPCLIENT : Write problem !"));
else
udpsocket->flush();
}
void UDP::readSocket()
{
while (udpsocket->hasPendingDatagrams())
{
QByteArray datagram;
datagram.resize(udpsocket->pendingDatagramSize());
qDebug() << udpsocket->pendingDatagramSize();
udpsocket->readDatagram(datagram.data(), datagram.size(), host, &port);
emit dataReceived(datagram);
}
}