我正在尝试从连接LAN的红外摄像机获取数据。 我不知道如何处理来自外部网络的数据包。 这是我的代码。
以下代码在Qt 5.9.7(msvc2017_64)上运行。我已从Qt UDP示例更改了代码。 (https://www.bogotobogo.com/Qt/Qt5_QUdpSocket.php)
#include "myudp.h"
MyUDP::MyUDP(QObject *parent) :
QObject(parent)
{
// create a QUDP socket
socket = new QUdpSocket(this);
socket_cam = new QUdpSocket(this);
// The most common way to use QUdpSocket class is
// to bind to an address and port using bind()
// bool QAbstractSocket::bind(const QHostAddress & address,
// quint16 port = 0, BindMode mode = DefaultForPlatform)
socket->bind(QHostAddress::LocalHost, 1234);
connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()));
}
void MyUDP::HelloUDP()
{
QByteArray Data;
QHostAddress camera_loc = QHostAddress("192.168.10.197");
quint16 cameraPort = 32197;
qint64 deg_num = socket->readDatagram(Data.data() ,964, &camera_loc,
&cameraPort);
qDebug() << "Deg_num: " << deg_num; //this returns -1. Therefore, it
seems it can't read any data from camera_loc.
// Sends the datagram datagram
// to the host address and at port.
// qint64 QUdpSocket::writeDatagram(const QByteArray & datagram,
// const QHostAddress & host, quint16 port)
socket->writeDatagram(Data, QHostAddress::LocalHost, 1234);
}
void MyUDP::readyRead()
{
// when data comes in
QByteArray buffer;
buffer.resize(socket->pendingDatagramSize());
QHostAddress sender = QHostAddress("192.168.10.197");
quint16 senderPort = 32197;
// qint64 QUdpSocket::readDatagram(char * data, qint64 maxSize,
// QHostAddress * address = 0, quint16 * port = 0)
// Receives a datagram no larger than maxSize bytes and stores it
// The sender's host address and port is stored in *address and *port
// (unless the pointers are 0).
socket->readDatagram(buffer.data(), buffer.size(),
&sender, &senderPort);
qDebug() << "Message from: " << sender.toString();
qDebug() << "Message port: " << senderPort;
qDebug() << "Message: " << buffer;
}
正如我在Wireshark上看到的那样,数据包按预期正确到达。 但是,我的代码无法正常工作。 (camera_loc上的readDatagram返回(-1)) 根据其他线程,我们不需要连接它们,因为UDP通信不需要建立连接。 我想用这段代码制作如下。
(0。使用readDatagram将来自摄像机(192.168.10.197)的数据保存在变量上)我不确定这是否是真正必要的过程... 1.按照此代码中的说明将数据写入缓冲区(使用writeDatagram函数)。
即使我挣扎,我也找不到解决方案。 我以为这很容易,但事实并非如此。 任何建议将不胜感激,因为我是qt和UDP网络的新手。
先谢谢了。