【QT】QT的学习:QUdpSocket的使用

简单的介绍使用QUdpSocket进行收发报文的用法:

发送方:

1.在Pro中添加QT += network

2.在头文件中添加:

class QUdpSocket;

private:
    QUdpSocket *senders;

3.在 c文件的构造函数中添加对象的初始化:

senders = new QUdpSocket(this);

4.在ui文件中添加一个button并转到槽:

void sender::on_pushButton_clicked()
{
    QByteArray datagram = "hello word!";
    senders->writeDatagram(datagram.data(), datagram.size(), QHostAddress::Broadcast,45454);
}

发送方逐步完成,只要点击按钮就会发送广播信息。


接收方:

1.在Pro中添加QT += network

2.在头文件中添加:

class QUdpSocket;

private slots:
    void processPendingDatagram();

private:

QUdpSocket *receiver;

在c文件的构造函数中添加:

 receiver = new QUdpSocket(this);
    receiver->bind(45454,QUdpSocket::ShareAddress);
    connect(receiver,SIGNAL(readyRead()), this,SLOT(processPendingDatagram()));


void Recevier :: processPendingDatagram()
{
    while(receiver->hasPendingDatagrams())
    {
        QByteArray datagram;
        datagram.resize(receiver->pendingDatagramSize());

        receiver->readDatagram(datagram.data(),datagram.size());
        ui->label->setText(datagram);
    }
}


注意:

一开始的时候使用connect函数:

connect(receiver,&QUdpSocket::readyRead, this,&Receiver::processPendingDatagram);

在QT creator 4上变异没有问题,但是一旦一直到QT5上就会报:

 'receiver' is not a class or namespace

 connect(receiver, &QUdpSocket::readyRead, this,&receiver::processPendingDatagram);


不得已在QT5上修改成SIGNAl以及SLOT的形式。能够编译成功。


猜你喜欢

转载自blog.csdn.net/ipfpm/article/details/78457016