如何在Qt中创建UDP“client”以便他从服务器接收数据?

时间:2017-04-11 21:58:57

标签: c++ qt qudpsocket

因此,UDP服务器显然只是侦听某个端口并处理带有源和IP的PORT的字节数组:

// In this code, listener is QUdpSocket*
FileServer::FileServer(QObject *parent)
    : QObject(parent)
    , listener(new QUdpSocket(this))
{
    // bind to listening port
    listener->bind(QHostAddress::Any, 6660);

    connect(listener, &QUdpSocket::readyRead,
            this, &FileServer::readPendingDatagrams, Qt::QueuedConnection);
}

void FileServer::readPendingDatagrams()
{
    while (listener->hasPendingDatagrams()) {
        // This is how this is done in new QT
        //QNetworkDatagram datagram = listener->receiveDatagram();
        //processTheDatagram(datagram);
        // This is how it is done in old QT
        QByteArray datagram;
        datagram.resize(listener->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;

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

非常好。这实际上是有效的,因为我使用这个python片段进行了验证:

import socket
host="127.0.0.1"
port=6660
udp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp_sock.sendto(b'PING', (host, port))

字节数组甚至包含“PING”。所以我打算写一个客户。我假设客户端只使用QUdpSocket::sendDatagram发送数据。但他怎么能收到数据?

首先我想我会打电话给bind(SERVER_ADDRESS_HERE, 6660)。但显然他们不能同时听同一个端口。

那么如何为上面的服务器编写客户端?

1 个答案:

答案 0 :(得分:0)

您可以使用套接字的信号readyread()在您重新传输数据时执行一个插槽:

//put this in the MainWindow costructor
connect(socket, SIGNAL(readyread()), SLOT(slot()));

请记住让绑定开始从端口重新获取数据:

//this is the code to make the bind
socket->bind(port);

在插槽中,您可以编写此代码,以便在QString中保存您所记录的内容:

void MainWindow::slot(){

    QString data = "";
    while(socket->hasPendingDatagrams()) {

        QByteArray datagram;
        datagram.resize(socket->pendingDatagramSize());
        QHostAddress senderIP;
        quint64 senderPort;
        socket->readDatagram(datagram.data(), datagram.size(), &senderIP, &senderPort);

        //if you want to check if the sender was the server you can control senderIp

        data += QString(datagram);
    }
}