【问题标题】:How to write a C++ socket programming based UDP with QT?如何使用 QT 编写基于 UDP 的 C++ 套接字编程?
【发布时间】:2012-03-29 11:46:50
【问题描述】:

我正在尝试编写一个在 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”

我该怎么办?

【问题讨论】:

    标签: qt network-programming udp


    【解决方案1】:

    您需要一个事件循环来使用信号和槽(使用QCoreApplicationQApplicationQEventLoop)和一个QObject 派生类来托管槽。

    但是您可以通过使用函数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 地址)。 p>

    【讨论】:

    • @hamed:是的,它对我有用。我在 linux 上测试了代码(以 netcat 作为发送者)。
    • 但是由于您在问题中添加了“广播”,因此我相应地编辑了答案。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2013-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-17
      • 1970-01-01
      • 1970-01-01
      • 2012-12-08
      相关资源
      最近更新 更多