我想从服务器向客户端发送UDP数据包。我用C ++写的服务器/客户端代码没有问题。但是当我向QML信号发送消息时,出现的问题很少。
myudp.cpp类代码:
#include "myudp.h"
MyUDP::MyUDP(QObject *parent) : QObject(parent)
{
socket = new QUdpSocket(this);
socket->bind(QHostAddress::LocalHost, 5824);
connect(socket,SIGNAL(readyRead()),this, SLOT(readyRead()));
}
// send message in client mode
void MyUDP::SayHello()
{
QByteArray Data;
Data.append("test message");
socket->writeDatagram(Data,QHostAddress::LocalHost,5824);
// 192.168.0.100
}
void MyUDP::readyRead()
{
QByteArray Buffer;
Buffer.resize(socket->pendingDatagramSize());;
QHostAddress sender;
quint16 senderPort;
socket->readDatagram(Buffer.data(),Buffer.size(), &sender, &senderPort);
qDebug()<< "Message:" << Buffer;
setType(Buffer);
}
QByteArray MyUDP::type()
{
return _type;
}
void MyUDP::setType(const QByteArray &t)
{
_type = t;
emit typeChanged();
}
myudp.h
#include <QObject>
#include <QUdpSocket>
class MyUDP : public QObject
{
Q_OBJECT
Q_PROPERTY(QByteArray type READ type WRITE setType NOTIFY typeChanged)
public:
explicit MyUDP(QObject *parent = 0);
void SayHello();
QByteArray type();
void setType(const QByteArray &t);
signals:
void typeChanged();
public slots:
void readyRead();
private:
QUdpSocket *socket;
QByteArray _type;
};
为客户端和服务器端定义的myudp类。
客户端的main.c:
#include "qtquick1applicationviewer.h"
#include <QApplication>
#include "myudp.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QtQuick1ApplicationViewer viewer;
viewer.addImportPath(QLatin1String("modules"));
viewer.setOrientation(QtQuick1ApplicationViewer::ScreenOrientationAuto);
viewer.setMainQmlFile(QLatin1String("qrc:/main.qml"));
viewer.showExpanded();
MyUDP client;
client.SayHello();
return app.exec();
}
服务器端的main.c连接到qml:
#include "qtquick1applicationviewer.h"
#include <QApplication>
#include <QCoreApplication>
#include <QDeclarativeEngine>
#include <QDeclarativeComponent>
#include <QDebug>
#include "myudp.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
qmlRegisterType<MyUDP>("MyUDP", 1,0, "MyUDP");
QDeclarativeEngine engine;
QDeclarativeComponent component(&engine, QUrl("qrc:/main.qml"));
MyUDP *myUDP = qobject_cast<MyUDP *>(component.create());
QtQuick1ApplicationViewer viewer;
viewer.addImportPath(QLatin1String("modules"));
viewer.setOrientation(QtQuick1ApplicationViewer::ScreenOrientationAuto);
viewer.setMainQmlFile(QLatin1String("qrc:/main.qml"));
viewer.showExpanded();
return app.exec();
}
最后是服务器端的main.qml:
import QtQuick 1.1
import MyUDP 1.0
Rectangle {
width: 360
height: 360
Text {
id: txt
text: qsTr("Hello World")
anchors.centerIn: parent
}
MyUDP{
id: myUdp
onTypeChanged: {
txt.text = "recived msg:" + type;
console.log("recived massage is " + type)
}
}
}
我从客户端向服务器发送消息,服务器在c ++区域正确接收消息,之后我将此消息发送给QML。在QML中console.log("recived massage is " + type)
正确打印消息数据,但txt.text = "recived msg:" + type;
未触发,文本文件中没有显示任何内容。
我很困惑为什么会这样!