QThread中执行UDP发送

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhango5/article/details/73274658

参照文章《解析Qt中QThread使用方法》(http://mobile.51cto.com/symbian-268690.htm)修改得来。


代码如下:


dummy.h


#ifndef DUMMY_H
#define DUMMY_H

#include <QObject>

class Dummy : public QObject
{
    Q_OBJECT
public:
    explicit Dummy(QObject *parent = 0){};

signals:
    void sig();
public slots:
    void emitsig()
    {
        emit sig();
    }
};

#endif // DUMMY_H

sendhandle.h


#ifndef SENDHANDLE_H
#define SENDHANDLE_H

#include <QUdpSocket>
#include <QDebug>

class SendHandle : public QObject
{
    Q_OBJECT
public:
    SendHandle();

    void init();

private slots:
    void sendfff();
private:
    QUdpSocket* sender;
};

#endif // SENDHANDLE_H

sendhandle.cpp


扫描二维码关注公众号,回复: 3865995 查看本文章
#include "sendhandle.h"

SendHandle::SendHandle()
    : sender(NULL)
{

}

void SendHandle::init()
{
    sender = new QUdpSocket();

    if (!sender->open(QIODevice::ReadWrite))
    {
        qDebug() << "open send udp socket failed.";
    }
}

void SendHandle::sendfff()
{
    if (NULL == sender)
    {
        init();
    }
    unsigned int uiRet = 0;

    char szBuf[] = "aa55aa55aa55aa55";

    QHostAddress _addr("192.168.1.255");
    uiRet = sender->writeDatagram(szBuf, strlen(szBuf)
           , _addr/*QHostAddress::Broadcast*/, 8888);

    qDebug() << uiRet;
}


main.cpp


#include <QtCore/QCoreApplication>
#include <QtCore/QObject>
#include <QThread>
#include <sendhandle.h>
#include "dummy.h"

int main (int argc, char* argv[])
{
    QCoreApplication a(argc, argv);

    QThread thread;

    SendHandle handle;

    Dummy dummy;

    handle.moveToThread(&thread);

    if (!QObject::connect(&dummy, SIGNAL(sig()), &handle, SLOT(sendfff())))
    {
        qDebug() << "connect failed.";
    }
    thread.start();
    dummy.emitsig();
    return a.exec();
}


猜你喜欢

转载自blog.csdn.net/zhango5/article/details/73274658
今日推荐