如何用QT编写基于UDP的C ++套接字编程?

时间:2012-03-29 11:46:50

标签: qt network-programming udp

我正在尝试编写一个在linux中读取广播UDP数据报的程序。我是套接字编程的初学者。
我的代码是:

#include <QUdpSocket>
#include <iostream>


int main ()
{
    QUdpSocket *udpSocket ;
    udpSocket= new QUdpSocket(0);
    udpSocket->bind(QHostAddress::LocalHost, 3838);


    udpSocket->connect(udpSocket, SIGNAL(readyRead()),
             this, SLOT(readPendingDatagrams()));

    while (1)
    {
        if (udpSocket->hasPendingDatagrams())
        {
             QByteArray datagram;
             datagram.resize(udpSocket->pendingDatagramSize());
             QHostAddress sender;
             quint16 senderPort;

             udpSocket->readDatagram(datagram.data(), datagram.size(),
                                     &sender, &senderPort);
        }
    }
}

但它会在this中返回错误。

  

main.cpp:13:18:错误:在非成员函数中无效使用'this'

我该怎么办?

2 个答案:

答案 0 :(得分:2)

您需要一个事件循环来使用信号和广告位(使用QCoreApplicationQApplicationQEventLoop)和QObject派生类来托管广告位。< / p>

但是你可以使用函数QUdpSocket::waitForReadyReadwaitForBytesWritten ......来同步使用没有信号/插槽或事件循环的套接字:

#include <QUdpSocket>
#include <QTextStream>

int main()
{
    QTextStream qout(stdout);

    QUdpSocket *udpSocket = new QUdpSocket(0);
    udpSocket->bind(3838, QUdpSocket::ShareAddress);

    while (udpSocket->waitForReadyRead(-1)) {
        while(udpSocket->hasPendingDatagrams()) {
            QByteArray datagram;
            datagram.resize(udpSocket->pendingDatagramSize());
            QHostAddress sender;
            quint16 senderPort;

            udpSocket->readDatagram(datagram.data(), datagram.size(),
                                    &sender, &senderPort);
            qout << "datagram received from " << sender.toString() << endl;
        }
    }
}

编辑:要收听广播UDP数据报,您也不应该收听QHostAddress::LocalHost,而应收听QHostAddress::Any(或至少收听连接到外部接口的IP地址) )。

答案 1 :(得分:0)

您不能使用主要功能的信号槽。您需要创建从QObject派生的新类,它创建套接字并将readyRead信号连接到您的类的插槽。

This example应该可以帮助您理解概念。