QT 多线程 TCP编程 ASSERT failure in QCoreApplication::sendEvent: “Cannot send events to objects 错误

该博客详细介绍了如何在C++中创建和管理UDP通信线程。通过创建UDPThread类,实例化QUdpSocket,并在工作函数中绑定端口进行数据收发。同时,利用QTimer实现定时发送消息,确保连接稳定性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述
这是另外一个UDP的例子,可以做参考:
入口:

    mUDPThread=new UDPThread();//这里参数不要加this,继承至QObject,用于管理自己QUdpSocket的成员变量,QUdpSocket的变量在入口函数以后实例化,不能在此处直接把成员变量也在构造函数直接实例化
    mUDPThread->setIPAndPORT(mUDPSendPORT,mUDPReceivePORT,mUDPIPStr);//把端口等信息传入到管理UDP的类内部
    QThread* sub = new QThread;
    mUDPThread->moveToThread(sub);
    sub->start();
    connect(this,&Communicator::startUDP,mUDPThread,&UDPThread::working);
    emit startUDP();//启动UDP线程

管理UDP的类,继承自QObject

class UDPThread : public QObject
{
    Q_OBJECT

public:
    QUdpSocket* receiveUDPSocket;//接收的套接字

    QHostAddress ip_Udp;
    quint16 portSend_Udp;
    quint16 portReceive_Udp;

    bool    ifReceiveFlag;//是否收到过反馈
    QByteArray heartBeatMesg;//心跳标志
    int invalidHeartCount;//发送的最大无效心跳次数

public:
    explicit UDPThread(QObject *parent = nullptr);
    ~UDPThread();
    
    // 工作函数
    void working();//入口函数,成员变量包括receiveUDPSocket,一般在这里面实例化
    void setIPAndPORT(quint16 m_sendPort,quint16 m_receivePort,QString m_IPStr);
private:
    void InitUDP();
    void UDPSendMessage();
    bool UDPReceiveMessage();
private:
    QTimer *mTimer;//指定时间间隔能指定间隔发送消息
};

入口函数:

void UDPThread::working()
{
	//重要就这个
    receiveUDPSocket=new QUdpSocket();//套接字实例化,别放到构造函数里面去

    if(ip_Udp==QHostAddress("")||portSend_Udp==NULL||portReceive_Udp==NULL){
        QLOG_WARN()<<"[UDP]ERRO: the IP ,sendPort,receivePort of UDP maybe = NULL ,please check IPandPort setup";
        return;
    }

    if(receiveUDPSocket->bind(portReceive_Udp,QAbstractSocket::ShareAddress)){
        QLOG_TRACE()<<"[UDP] bind to Port success And begin to connecting.....";
    }else {
        QLOG_WARN()<<"[UDP] UDP bind port fail";
    }
    connect(receiveUDPSocket,&QUdpSocket::readyRead,this,&UDPThread:: UDPReceiveMessage);
    //新增,当在正式连接后,中途出现中断,能以定时器间断发送消息
    mTimer =new QTimer(this);
    connect(mTimer, &QTimer::timeout, this,&UDPThread::UDPSendMessage);
    mTimer->setTimerType(Qt::PreciseTimer);// 修改定时器对象的精度
}
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

青鸟青史

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值