예제 #1
0
void UdpRelay::onSocketError()
{
    QUdpSocket *sock = qobject_cast<QUdpSocket *>(sender());
    if (!sock) {
        emit info("Fatal. A false object calling onSocketError.");
        return;
    }
    if (sock == &listenSocket) {
        emit info("[UDP] server socket error " + sock->errorString());
    } else {
        emit info("[UDP] client socket error " + sock->errorString());
    }
}
예제 #2
0
void tst_QUdpSocket::unconnectedServerAndClientTest()
{
    QUdpSocket serverSocket;

    qRegisterMetaType<QAbstractSocket::SocketState>("QAbstractSocket::SocketState");

    QSignalSpy stateChangedSpy(&serverSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)));
    QVERIFY2(serverSocket.bind(), serverSocket.errorString().toLatin1().constData());
    QCOMPARE(stateChangedSpy.count(), 1);

    const char *message[] = {"Yo mista", "Yo", "Wassap"};

    QHostAddress serverAddress = QHostAddress::LocalHost;
    if (!(serverSocket.localAddress() == QHostAddress::Any))
        serverAddress = serverSocket.localAddress();

    for (int i = 0; i < 3; ++i) {
        QUdpSocket clientSocket;
        QCOMPARE(int(clientSocket.writeDatagram(message[i], strlen(message[i]),
                                                serverAddress, serverSocket.localPort())),
                 int(strlen(message[i])));
        char buf[1024];
        QHostAddress host;
        quint16 port;
        QVERIFY(serverSocket.waitForReadyRead(5000));
        QCOMPARE(int(serverSocket.readDatagram(buf, sizeof(buf), &host, &port)),
                 int(strlen(message[i])));
        buf[strlen(message[i])] = '\0';
        QCOMPARE(QByteArray(buf), QByteArray(message[i]));
    }
}
예제 #3
0
bool EditorPipe::sendToEditor(QString command)
{
    QUdpSocket socket;
    // Attempt to connect to the LocalServer
    socket.connectToHost(QHostAddress::LocalHost, 58487);

    if(socket.waitForConnected(100))
    {
        qDebug() << "Connected";
        QString str = QString(command);
        QByteArray bytes;
        bytes = str.toUtf8();
        socket.write(bytes);
        socket.waitForBytesWritten(10000);
        socket.flush();
        socket.disconnectFromHost();
        qDebug() << "Bytes sent: " <<command;
        return true;
    }
    else
    {
        qDebug() << "sendToEditor(QString command) fail to connect: " << socket.errorString();
        return false;
    }
}
예제 #4
0
void tst_QUdpSocket::performance()
{
    QUdpSocket server;
    QVERIFY2(server.bind(), server.errorString().toLatin1().constData());

    QHostAddress serverAddress = QHostAddress::LocalHost;
    if (!(server.localAddress() == QHostAddress::Any))
        serverAddress = server.localAddress();

    QUdpSocket client;
    client.connectToHost(serverAddress, server.localPort());

    QByteArray arr(8192, '@');

    QTime stopWatch;
    stopWatch.start();

    qint64 nbytes = 0;
    while (stopWatch.elapsed() < 5000) {
        for (int i = 0; i < 100; ++i) {
            if (client.write(arr.data(), arr.size()) > 0) {
                do {
                    nbytes += server.readDatagram(arr.data(), arr.size());
                } while (server.hasPendingDatagrams());
            }
        }
    }

    float secs = stopWatch.elapsed() / 1000.0;
    qDebug("\t%.2fMB/%.2fs: %.2fMB/s", float(nbytes / (1024.0*1024.0)),
           secs, float(nbytes / (1024.0*1024.0)) / secs);
}
예제 #5
0
void NewRefereeModule::run() {
    QUdpSocket socket;

    if (!socket.bind(ProtobufRefereePort, QUdpSocket::ShareAddress)) {
        throw runtime_error("Can't bind to shared referee port");
    }

    multicast_add(&socket, RefereeAddress);

    _packets.reserve(4);

    _running = true;
    while (_running) {
        if (!_useExternalRef) continue;

        char buf[65536];

        if (!socket.waitForReadyRead(500)) {
            continue;
        }

        QHostAddress host;
        quint16 port = 0;
        qint64 size = socket.readDatagram(buf, sizeof(buf), &host, &port);
        if (size < 1) {
            fprintf(stderr, "NewRefereeModule: %s/n",
                    (const char*)socket.errorString().toLatin1());
            ::usleep(100000);
            continue;
        }

        NewRefereePacket* packet = new NewRefereePacket;
        packet->receivedTime = RJ::timestamp();
        this->received_time = packet->receivedTime;
        if (!packet->wrapper.ParseFromArray(buf, size)) {
            fprintf(stderr,
                    "NewRefereeModule: got bad packet of %d bytes from %s:%d\n",
                    (int)size, (const char*)host.toString().toLatin1(), port);
            fprintf(stderr, "Packet: %s\n", buf);
            fprintf(stderr, "Address: %s\n", RefereeAddress);
            continue;
        }

        _mutex.lock();
        _packets.push_back(packet);

        stage = (Stage)packet->wrapper.stage();
        command = (Command)packet->wrapper.command();
        sent_time = packet->wrapper.packet_timestamp();
        stage_time_left = packet->wrapper.stage_time_left();
        command_counter = packet->wrapper.command_counter();
        command_timestamp = packet->wrapper.command_timestamp();
        yellow_info.ParseRefboxPacket(packet->wrapper.yellow());
        blue_info.ParseRefboxPacket(packet->wrapper.blue());
        ballPlacementx = packet->wrapper.designated_position().x();
        ballPlacementy = packet->wrapper.designated_position().y();

        _mutex.unlock();
    }
}
예제 #6
0
void ClientSktUdp::error()
{
    QUdpSocket* s = qobject_cast<QUdpSocket*>(sender());

    show(QString("UDP socket error %1, %2").arg(s->error()).arg(s->errorString()));

    unplug();
}
/**
 * @details
 * Constructs a new QIODevice (in this case a QUdpSocket) and returns it
 * after binding the socket to the port specified in the XML node and read by
 * the constructor of the abstract chunker.
 */
QIODevice* LofarDataSplittingChunker::newDevice()
{
    QUdpSocket* socket = new QUdpSocket;

    if (!socket->bind(port(), QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint ))
        cerr << "LofarDataSplittingChunker::newDevice(): "
        "Unable to bind to UDP port!" <<
        socket->errorString().toStdString() << std::endl;

    return socket;
}
예제 #8
0
void tst_QUdpSocket::broadcasting()
{
    QFETCH_GLOBAL(bool, setProxy);
    if (setProxy) {
#ifdef TEST_QNETWORK_PROXY
        QFETCH_GLOBAL(int, proxyType);
        if (proxyType == QNetworkProxy::Socks5Proxy) {
            QSKIP("With socks5 Broadcast is not supported.", SkipAll);
        }
#endif
    }
#ifdef Q_OS_AIX
    QSKIP("Broadcast does not work on darko", SkipAll);
#endif
    const char *message[] = {"Yo mista", "", "Yo", "Wassap"};

    for (int i = 0; i < 4; ++i) {
        QUdpSocket serverSocket;
        QVERIFY2(serverSocket.bind(QHostAddress::Any, 5000), serverSocket.errorString().toLatin1().constData());

        QCOMPARE(serverSocket.state(), QUdpSocket::BoundState);

        connect(&serverSocket, SIGNAL(readyRead()), SLOT(empty_readyReadSlot()));

        QUdpSocket broadcastSocket;

        for (int j = 0; j < 100; ++j) {
            broadcastSocket.writeDatagram(message[i], strlen(message[i]),
                                          QHostAddress::Broadcast, 5000);
            QTestEventLoop::instance().enterLoop(15);
            if (QTestEventLoop::instance().timeout()) {
#if defined(Q_OS_FREEBSD)
                QEXPECT_FAIL("",
                             "Broadcasting to 255.255.255.255 does not work on FreeBSD",
                             Abort);
                QVERIFY(false); // seems that QFAIL() doesn't respect the QEXPECT_FAIL() :/
#endif
                QFAIL("Network operation timed out");
            }
            QVERIFY(serverSocket.hasPendingDatagrams());

            do {
                QByteArray arr;
                arr.resize(serverSocket.pendingDatagramSize() + 1);
                QHostAddress host;
                quint16 port;
                QCOMPARE((int) serverSocket.readDatagram(arr.data(), arr.size() - 1, &host, &port),
                         (int) strlen(message[i]));
                arr.resize(strlen(message[i]));
                QCOMPARE(arr, QByteArray(message[i]));
            } while (serverSocket.hasPendingDatagrams());
        }
    }
}
예제 #9
0
// Constructs a new QIODevice (in this case a QUdpSocket) and returns it
// after binding the socket to the port specified in the XML node and read by
// the constructor of the abstract chunker.
QIODevice* K7Chunker::newDevice()
{
    QUdpSocket* udpSocket = new QUdpSocket;

    if (!udpSocket->bind(port(), QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint ))
    {
        std::cerr << "K7Chunker::newDevice(): Unable to bind to UDP port!" << udpSocket->errorString().toStdString() << std::endl;
    }

    return udpSocket;
}
예제 #10
0
void tst_QUdpSocket::loop()
{
    QFETCH(QByteArray, peterMessage);
    QFETCH(QByteArray, paulMessage);
    QFETCH(bool, success);

    QUdpSocket peter;
    QUdpSocket paul;

    QVERIFY2(peter.bind(), peter.errorString().toLatin1().constData());
    QVERIFY2(paul.bind(), paul.errorString().toLatin1().constData());

    QHostAddress peterAddress = QHostAddress::LocalHost;
    if (!(peter.localAddress() == QHostAddress::Any))
        peterAddress = peter.localAddress();
    QHostAddress pualAddress = QHostAddress::LocalHost;
    if (!(paul.localAddress() == QHostAddress::Any))
        pualAddress = paul.localAddress();

    QCOMPARE(peter.writeDatagram(peterMessage.data(), peterMessage.length(),
                                 pualAddress, paul.localPort()), qint64(peterMessage.length()));
    QCOMPARE(paul.writeDatagram(paulMessage.data(), paulMessage.length(),
                                peterAddress, peter.localPort()), qint64(paulMessage.length()));

    QVERIFY(peter.waitForReadyRead(5000));
    QVERIFY(paul.waitForReadyRead(5000));
    char peterBuffer[16*1024];
    char paulBuffer[16*1024];
    if (success) {
        QCOMPARE(peter.readDatagram(peterBuffer, sizeof(peterBuffer)), qint64(paulMessage.length()));
        QCOMPARE(paul.readDatagram(paulBuffer, sizeof(peterBuffer)), qint64(peterMessage.length()));
    } else {
        QVERIFY(peter.readDatagram(peterBuffer, sizeof(peterBuffer)) != paulMessage.length());
        QVERIFY(paul.readDatagram(paulBuffer, sizeof(peterBuffer)) != peterMessage.length());
    }

    QCOMPARE(QByteArray(peterBuffer, paulMessage.length()), paulMessage);
    QCOMPARE(QByteArray(paulBuffer, peterMessage.length()), peterMessage);
}
예제 #11
0
void tst_QUdpSocket::bindMode()
{
    QFETCH_GLOBAL(bool, setProxy);
    if (setProxy) {
#ifdef TEST_QNETWORK_PROXY
        QFETCH_GLOBAL(int, proxyType);
        if (proxyType == QNetworkProxy::Socks5Proxy) {
            QSKIP("With socks5 explicit port binding is not supported.", SkipAll);
        }
#endif
    }

    QUdpSocket socket;
    QVERIFY2(socket.bind(), socket.errorString().toLatin1().constData());
    QUdpSocket socket2;
    QVERIFY(!socket2.bind(socket.localPort()));

#ifdef Q_OS_UNIX
    QVERIFY(!socket2.bind(socket.localPort(), QUdpSocket::ReuseAddressHint));
    socket.close();
    QVERIFY2(socket.bind(0, QUdpSocket::ShareAddress), socket.errorString().toLatin1().constData());
    QVERIFY2(socket2.bind(socket.localPort()), socket2.errorString().toLatin1().constData());
    socket2.close();
    QVERIFY2(socket2.bind(socket.localPort(), QUdpSocket::ReuseAddressHint), socket2.errorString().toLatin1().constData());
#else
    // Depending on the user's privileges, this or will succeed or
    // fail. Admins are allowed to reuse the address, but nobody else.
    if (!socket2.bind(socket.localPort(), QUdpSocket::ReuseAddressHint), socket2.errorString().toLatin1().constData())
        qWarning("Failed to bind with QUdpSocket::ReuseAddressHint, user isn't an adminstrator?");
    socket.close();
    QVERIFY2(socket.bind(0, QUdpSocket::ShareAddress), socket.errorString().toLatin1().constData());
    QVERIFY(!socket2.bind(socket.localPort()));
    socket.close();
    QVERIFY2(socket.bind(0, QUdpSocket::DontShareAddress), socket.errorString().toLatin1().constData());
    QVERIFY(!socket2.bind(socket.localPort()));
    QVERIFY(!socket2.bind(socket.localPort(), QUdpSocket::ReuseAddressHint));
#endif
}
예제 #12
0
void tst_QUdpSocket::constructing()
{
    QUdpSocket socket;

    QVERIFY(socket.isSequential());
    QVERIFY(!socket.isOpen());
    QVERIFY(socket.socketType() == QUdpSocket::UdpSocket);
    QCOMPARE((int) socket.bytesAvailable(), 0);
    QCOMPARE(socket.canReadLine(), false);
    QCOMPARE(socket.readLine(), QByteArray());
    QCOMPARE(socket.socketDescriptor(), -1);
    QCOMPARE(socket.error(), QUdpSocket::UnknownSocketError);
    QCOMPARE(socket.errorString(), QString("Unknown error"));

    // Check the state of the socket api
}
예제 #13
0
void tst_QUdpSocket::pendingDatagramSize()
{
    QUdpSocket server;
    QVERIFY2(server.bind(), server.errorString().toLatin1().constData());

    QHostAddress serverAddress = QHostAddress::LocalHost;
    if (!(server.localAddress() == QHostAddress::Any))
        serverAddress = server.localAddress();

    QUdpSocket client;
    QVERIFY(client.writeDatagram("this is", 7, serverAddress, server.localPort()) == 7);
    QVERIFY(client.writeDatagram(0, 0, serverAddress, server.localPort()) == 0);
    QVERIFY(client.writeDatagram("3 messages", 10, serverAddress, server.localPort()) == 10);

    char c = 0;
    QVERIFY(server.waitForReadyRead());
    if (server.hasPendingDatagrams()) {
#if defined Q_OS_HPUX && defined __ia64
        QEXPECT_FAIL("", "HP-UX 11i v2 can't determine the datagram size correctly.", Abort);
#endif
        QCOMPARE(server.pendingDatagramSize(), qint64(7));
        c = '\0';
        QCOMPARE(server.readDatagram(&c, 1), qint64(1));
        QCOMPARE(c, 't');
        c = '\0';
    } else {
        QSKIP("does not have the 1st datagram", SkipSingle);
    }

    if (server.hasPendingDatagrams()) {
        QCOMPARE(server.pendingDatagramSize(), qint64(0));
        QCOMPARE(server.readDatagram(&c, 1), qint64(0));
        QCOMPARE(c, '\0'); // untouched
        c = '\0';
    } else {
        QSKIP("does not have the 2nd datagram", SkipSingle);
    }

    if (server.hasPendingDatagrams()) {
        QCOMPARE(server.pendingDatagramSize(), qint64(10));
        QCOMPARE(server.readDatagram(&c, 1), qint64(1));
        QCOMPARE(c, '3');
    } else {
        QSKIP("does not have the 3rd datagram", SkipSingle);
    }
}
예제 #14
0
bool UDPSocket::sendUDPDatagramWithAnyPort(const QHostAddress &targetAddress, quint16 targetPort, const QByteArray &data, QString *errorString){
    qDebug()<<"UDPSocket::sendUDPDatagram(...)-targetAddress:"<<targetAddress.toString()<<" targetPort:"<<targetPort;

    QUdpSocket udpSocket;
    qint64 size = udpSocket.writeDatagram(data, targetAddress, targetPort);
    if(errorString){
        *errorString = udpSocket.errorString();
    }

    if(size == -1){
        qCritical()<<QString("UDP Datagram Sent Failed! Target Address:%1, Port:%2, %3").arg(targetAddress.toString()).arg(targetPort).arg(udpSocket.errorString());
        return false;
    } 

    return (size == data.size())?true:false;;

}
예제 #15
0
void tst_QUdpSocket::writeDatagram()
{
    QUdpSocket server;
    QVERIFY2(server.bind(), server.errorString().toLatin1().constData());

    QHostAddress serverAddress = QHostAddress::LocalHost;
    if (!(server.localAddress() == QHostAddress::Any))
        serverAddress = server.localAddress();

    QUdpSocket client;

    qRegisterMetaType<qint64>("qint64");
    qRegisterMetaType<QAbstractSocket::SocketError>("QAbstractSocket::SocketError");

    for(int i=0;; i++) {
        QSignalSpy errorspy(&client, SIGNAL(error(QAbstractSocket::SocketError)));
        QSignalSpy bytesspy(&client, SIGNAL(bytesWritten(qint64)));

        qint64 written = client.writeDatagram(QByteArray(i * 1024, 'w'), serverAddress,
                                              server.localPort());

        if (written != i * 1024) {
#if defined (Q_OS_HPUX)
            QSKIP("HP-UX 11.11 on hai (PA-RISC 64) truncates too long datagrams.", SkipSingle);
#endif
            QCOMPARE(bytesspy.count(), 0);
            QCOMPARE(errorspy.count(), 1);
            QCOMPARE(*static_cast<const int *>(errorspy.at(0).at(0).constData()),
                     int(QUdpSocket::DatagramTooLargeError));
            QCOMPARE(client.error(), QUdpSocket::DatagramTooLargeError);
            break;
        }
        QVERIFY(bytesspy.count() == 1);
        QCOMPARE(*static_cast<const qint64 *>(bytesspy.at(0).at(0).constData()),
                 qint64(i * 1024));
        QCOMPARE(errorspy.count(), 0);
        if (!server.waitForReadyRead(5000))
            QSKIP(QString("UDP packet lost at size %1, unable to complete the test.").arg(i * 1024).toLatin1().data(), SkipSingle);
        QCOMPARE(server.pendingDatagramSize(), qint64(i * 1024));
        QCOMPARE(server.readDatagram(0, 0), qint64(0));
    }
}
void VisionReceiver::run() {
    QUdpSocket socket;

    // Create vision socket
    if (simulation) {
        // The simulator doesn't multicast its vision.  Instead, it sends to two
        // different ports.
        // Try to bind to the first one and, if that fails, use the second one.
        if (!socket.bind(SimVisionPort)) {
            if (!socket.bind(SimVisionPort + 1)) {
                throw runtime_error(
                    "Can't bind to either simulated vision port");
            }
        }
    } else {
        // Receive multicast packets from shared vision.
        if (!socket.bind(port, QUdpSocket::ShareAddress)) {
            throw runtime_error("Can't bind to shared vision port");
        }

        multicast_add(&socket, SharedVisionAddress);
    }

    // There should be at most four packets: one for each camera on each of two
    // frames, assuming some clock skew between this
    // computer and the vision computer.
    _packets.reserve(4);

    _running = true;
    while (_running) {
        char buf[65536];

        // Wait for a UDP packet
        if (!socket.waitForReadyRead(500)) {
            // Time out once in a while so the thread has a chance to exit
            continue;
        }

        QHostAddress host;
        quint16 portNumber = 0;
        qint64 size = socket.readDatagram(buf, sizeof(buf), &host, &portNumber);
        if (size < 1) {
            fprintf(stderr, "VisionReceiver: %s\n",
                    (const char*)socket.errorString().toLatin1());
            // See Processor for why we can't use QThread::msleep()
            ::usleep(100 * 1000);
            continue;
        }

        // FIXME - Verify that it is from the right host, in case there are
        // multiple visions on the network

        // Parse the protobuf message
        VisionPacket* packet = new VisionPacket;
        packet->receivedTime = timestamp();
        if (!packet->wrapper.ParseFromArray(buf, size)) {
            fprintf(stderr,
                    "VisionReceiver: got bad packet of %d bytes from %s:%d\n",
                    (int)size, (const char*)host.toString().toLatin1(),
                    portNumber);
            continue;
        }

        // Add to the vector of packets
        _mutex.lock();
        _packets.push_back(packet);
        _mutex.unlock();
    }
}
예제 #17
0
파일: Discover.cpp 프로젝트: dustyco/Drone
void Discover::announceRecords ()
{
	// Reset timer
	timer->start(announcePeriodMsec);

	if (not running) return;

	// Servers don't announce periodically or send departure messages
	if (mServerMode) return;

	// Start building a list of records to send in each scope
	QList<Record> recordsToSend;

	///////////////////////////////////////////////////////////////////////
	// Global scope first
	///////////////////////////////////////////////////////////////////////
	for (Record record : ownedRecords)
	if (record["Scope"] == "Global")
	{
		recordsToSend.push_back(record);
	}
	if (not recordsToSend.empty() or defaultScope=="Global")
	{
		// This is a discovery request which should be responded to
		QByteArray datagram("DSDR");
		if (departure) datagram = "DSDD";
		datagram += makeDatagram(recordsToSend, false);

		// Send to each Global server
		for (QPair<QHostAddress,quint16> globalServer : globalServers)
		{
			globalSocket->writeDatagram(datagram, globalServer.first, globalServer.second);
		}
	}

	///////////////////////////////////////////////////////////////////////
	// Local scope next
	///////////////////////////////////////////////////////////////////////
	for (Record record : ownedRecords)
	if (record["Scope"] == "Local")
	{
		recordsToSend.push_back(record);
	}
	if (not recordsToSend.empty() or defaultScope=="Global" or defaultScope=="Local")
	{
		QByteArray datagram("DSDA");
		if (announceNeedsResponse) datagram = "DSDR";
		if (departure)             datagram = "DSDD";
		datagram += makeDatagram(recordsToSend, true);

		// For each interface
		for (auto iface : QNetworkInterface::allInterfaces())
		{
			// For each IPv4 address on this interface
			for (auto entry : iface.addressEntries())
			{
				if (entry.ip().protocol() != QAbstractSocket::IPv4Protocol) continue;

				// Add it to addressEntryCache if necessary for local scope testing
				if (not addressEntryCache.contains(entry)) addressEntryCache.push_back(entry);

				// Multicast
				if (iface.flags().testFlag(QNetworkInterface::CanMulticast) and !entry.ip().isNull() and !entry.ip().isLoopback())
				{
					// Create the socket if it doesn't exit yet
					if (not multiSocket.contains(entry.ip().toString()))
					{
						logDebug(QString("New multicast socket: %1 %2").arg(entry.ip().toString(), entry.netmask().toString()));

						// Add it, create and bind the socket
						QUdpSocket* socket = new QUdpSocket(this);
						connect(socket, SIGNAL(readyRead()), this, SLOT(readDatagrams()));
						socket->setSocketOption(QAbstractSocket::MulticastTtlOption, 1);
						if (not socket->bind(QHostAddress::AnyIPv4, port, QAbstractSocket::ShareAddress | QAbstractSocket::ReuseAddressHint))
						{
							logWarning(QString("Error binding to iface %1: %2").arg(entry.ip().toString(), socket->errorString()));
						}
						socket->setMulticastInterface(iface);
						socket->joinMulticastGroup(groupAddress, iface);
						multiSocket.insert(entry.ip().toString(), socket);
					}

					// Send datagram
					multiSocket[entry.ip().toString()]->writeDatagram(datagram, groupAddress, port);
				}
			}
		}
	}

	///////////////////////////////////////////////////////////////////////
	// Loopback scope last
	///////////////////////////////////////////////////////////////////////
	for (Record record : ownedRecords)
	if (record["Scope"] == "Loopback")
	{
		recordsToSend.push_back(record);
	}
	if (not recordsToSend.empty() or true) // Any scope is above or equivalent to loopback
	{
		QByteArray datagram("DSDA");
		if (announceNeedsResponse) datagram = "DSDR";
		if (departure)             datagram = "DSDD";
		datagram += makeDatagram(recordsToSend, true);

		// Loopback
		//loopbackSocket->writeDatagram(datagram, QHostAddress::LocalHost, port);
	}

	// Reset
	announceNeedsResponse = false;
	departure = false;
}
예제 #18
0
QString RoboControllerSDK::findServer(quint16 udpSendPort/*=14550*/ , quint64 udpListenPort/*=14555*/)
{
    /*if( mUdpConnected )
        return mServerAddr;*/

    QUdpSocket* udp = new QUdpSocket();
    if( !udp->bind( udpListenPort, QAbstractSocket::ReuseAddressHint|QAbstractSocket::ShareAddress ) )
    {
        qDebug() << tr("UDP error: %1").arg(udp->errorString() );
        delete udp;
        return QString();
    }

    QVector<quint16> vec;

    // >>>>> sendCommand( udp, CMD_SERVER_PING_REQ, vec  );
    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_5_2);
    out << (quint16)0;    // Block size
    out << (quint16)1;    // Message counter
    out << (quint16)CMD_SERVER_PING_REQ;       // Message Code

    out.device()->seek(0);          // Back to the beginning to set block size
    int blockSize = (block.size() - sizeof(quint16));
    out << (quint16)blockSize;

    udp->writeDatagram( block, QHostAddress::Broadcast, udpSendPort);
    // <<<<< sendCommand( udp, CMD_SERVER_PING_REQ, vec  );

    msleep( 500 );

    if( udp->waitForReadyRead( 10000 ) )
    {
        QHostAddress addr;
        quint16 port;

        char data[256];

        qint64 readCount = udp->readDatagram( data, 256, &addr, &port );

        if( readCount==0 )
            return QString();

        for( int i=0; i<readCount; i++ )
        {
            if( data[i]==MSG_SERVER_PING_OK )
            {
                if( i>2 && data[i-4]==4 ) // The block size must be 4
                {
                    delete udp;
                    return addr.toString();
                }
            }
        }

        delete udp;
        return QString(); // Correct MSG_SERVER_PING_OK not found!
    }
    else
    {
        delete udp;
        return QString();
    }
}
예제 #19
0
int udp_ping(QStringList command) {
    qDebug() << "udp_ping(" << command.join(" ") << ")" << endl;
    qDebug() << "udp_ping(" << command.join(" ") << ")" << endl;

    /**
     * Check input
     */
    QTextStream errorStream(stderr);

    if(command.size() != 3 || command.at(0)!="ping" || command.at(1)!="udp" ) {

        errorStream << "Error: udp_ping(" << command.join(" ") << ") is no valid call (ping udp <ip_address> <port> rzv|max|random|default)" << endl;
        return 1;
    }


    /**
     * <functionality>
     */


    QByteArray byteArray;

    /**
     * CIP for "rzv"
     */
    if(command.at(2)=="rzv") {
        qDebug() << "rzv" << endl;

        byteArray.append(QByteArray(42, '\0'));
     }


    /**
     * Sent via TCP
     */
    QUdpSocket *udpSocket;
    udpSocket = new QUdpSocket();
    QTextStream outStream(stdout);

    QString out;

    udpSocket->abort();
    udpSocket->connectToHost("127.0.0.1", 22366);

    qDebug() << "waitForConnected!";
    if (udpSocket->waitForConnected(5000)) {
        qDebug() << "Connected!";
    }
    else {
        errorStream << "Error: udp_ping(" << command.join(" ") << "): No connection available!" << endl;
        return 1;
    }

    qDebug() << QString("BytesWritten: %1").arg(udpSocket->write(byteArray, byteArray.length()));
    udpSocket->flush();

    int numRead = 0, numReadTotal = 0;
    char buffer[MAXMSG];

    forever {
        numRead  = udpSocket->read(buffer, MAXMSG);
        qDebug() << "read buffer: " << numRead;

        numReadTotal += numRead;
        if (numRead <= 0 && !udpSocket->waitForReadyRead(30))
            break;
    }
    qDebug() << numReadTotal << " bytes red";

    if(numReadTotal==-1) {
        errorStream << "Error: udp_ping(" << command.join(" ") << "): " << udpSocket->errorString() << endl;
        return 1;
    }
    else {
        for(int i=0; i < numReadTotal; i++) {
            qDebug() << QString("receipt[%1]: %2\n").arg(i).arg(buffer[i], 8, 2, QLatin1Char('0')) << endl;;
        }
        QByteArray receipt(buffer);


        qDebug() << "receipt.size(): " << receipt.size();

        for(int i = 0; i < receipt.size();++i) {
           qDebug() << QString("receipt[%1]: %2\n").arg(i).arg(receipt.at(i), 8, 2, QLatin1Char('0')) << endl;;
        }
        qDebug() << "buffer: " << buffer;
    }

    udpSocket->disconnectFromHost();
    udpSocket->close();

    outStream << out << endl;

    return 0;
}