void RemoteInterfaceListener::run() {

	// Init socket
	stopRequested = false;
	QUdpSocket socket;
	if(!socket.bind(QHostAddress(server->ip), server->port, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint)) {
		// Show error
		Debug::print("[RemoteInterfaceListener] could not bind");
		stopRequested = true;
	}

	// Enter processing loop...
	while (stopRequested == false) {

		// Process all pending datagrams
		while(socket.hasPendingDatagrams() && !stopRequested) {
			// Get the data from socket
			QByteArray data;
			data.resize(socket.pendingDatagramSize());
			QHostAddress sender;
			quint16 senderPort;
			socket.readDatagram(data.data(), data.size(), &sender, &senderPort);

			// Extract message and keep track of the pointer in the server
			RemoteInterfaceMessage *message = new RemoteInterfaceMessage(&data);
			message->sourceIp = sender.toString();
			message->sourcePort = senderPort;
			message->destinationIp = server->ip;
			message->destinationPort = server->port;
			server->messages->append(message);

			// Show reception and pass on for processing...
			Debug::print("[RemoteInterfaceListener] received %1 message from %2:%3", message->type, sender.toString(), senderPort);
			server->processMessage(message);
		}

		// Sleep wait
		QThread::msleep(core->intSetting("RemoteInterface_ListenerInterval"));

	}
}
Beispiel #2
0
QString connection::Broadcast() {
    // Om ip adressen te ontdekken
    QNetworkAddressEntry inter;
    // sockets aanmaken en verbinden met enerzijds broadcast en anderzijds een luister poort
    QUdpSocket udpSocketSend;
    QUdpSocket udpSocketGet;
    udpSocketSend.connectToHost(inter.broadcast(), 40000);
    // udpSocketGet->bind(inter->ip(),667);
    // udpSocketGet->bind(QHostAddress::Any,667)
    if(udpSocketGet.bind(udpgetport,QUdpSocket::ShareAddress))
        Label->setText(Label->text() + "[INFO] Could properly bind udpSocketget to " + QString::number(udpgetport) + "\n");
    else Label->setText(Label->text() + "[INFO] Couldn't properly bind udpSocketget to " + QString::number(udpgetport) + "\n");
    // Pakket verzenden
    QByteArray send_datagram = "DISCOVER-STRATEGO-SERVER";
    // Optimalisatie voor in de loop
    QByteArray receive_datagram;

    quint16 serverPort;
    forever{
        udpSocketSend.writeDatagram(send_datagram, QHostAddress::Broadcast, 40000);
        if(udpSocketGet.waitForReadyRead(3000)){
            receive_datagram.resize(udpSocketGet.pendingDatagramSize());
            udpSocketGet.readDatagram(receive_datagram.data(),receive_datagram.size(),&server,&serverPort);
            if(QString::fromUtf8(receive_datagram.data()) == "DISCOVERED-STRATEGO-SERVER")
            {
                receive_datagram.resize(udpSocketGet.pendingDatagramSize());
                udpSocketGet.readDatagram(receive_datagram.data(),receive_datagram.size(),&server,&serverPort);
                Label->setText(Label->text() +"[INFO] PLAYER DATA: "+ receive_datagram.data() +"\n");
                speler = receive_datagram.toInt();
                if(speler==1)
                {
                    attacker=true;
                }
                else
                {
                    attacker=false;
                }
                receive_datagram.resize(udpSocketGet.pendingDatagramSize());
                udpSocketGet.readDatagram(receive_datagram.data(),receive_datagram.size(),&server,&serverPort);
                Label->setText(Label->text() + "[INFO] GAME DATA: "+receive_datagram.data()+"\n");
                spel = receive_datagram.toInt();
                Label->setText(Label->text() + " SPEL:" + QString::number(spel) + "\n");
                Label->setText(Label->text() + "[INFO] Found STRATEGO-SERVER on " + server.toString().toUtf8().constData() + "\n");
                return server.toString();
            }
        }
        else
        {
            Label->setText(Label->text() + "[INFO] UDP Discover TimeOut!\n");
            static int timeout=0;
            timeout++;
            if(timeout==5)
            {
                Label->setText(Label->text() + "[ERROR] Server is not online. Please try again later!");
                return "";
            }
        }
    }
    return "";
}
// Called whenever there is data available on the device.
void SignalChunker::next(QIODevice* device)
{
    // Get a pointer to the UDP socket.
    QUdpSocket* udpSocket = static_cast<QUdpSocket*>(device);
    _bytesRead = 0;

    // Get writable buffer space for the chunk.
    WritableData writableData = getDataStorage(_chunkSize);
    if (writableData.isValid()) {
        // Get pointer to start of writable memory.
        char* ptr = (char*) (writableData.ptr());

        // Read datagrams for chunk from the UDP socket.
        while (isActive() && _bytesRead < _chunkSize) {
            // Read the datagram, but avoid using pendingDatagramSize().
            if (!udpSocket->hasPendingDatagrams()) {
                // MUST WAIT for the next datagram.
                udpSocket->waitForReadyRead(100);
                continue;
            }
            qint64 maxlen = _chunkSize - _bytesRead;
            qint64 length = udpSocket->readDatagram(ptr + _bytesRead, maxlen);
            if (length > 0)
                _bytesRead += length;
        }
    }

    // Must discard the datagram if there is no available space.
    else {
        udpSocket->readDatagram(0, 0);
    }
}
Beispiel #4
0
void Connection::slReceive() {
	QUdpSocket* sock = (QUdpSocket*) QObject::sender();
	const bool main = (sock->localPort() == sets.portMain) ? true : false;
	const bool aux = (sock->localPort() == sets.portAux) ? true : false;

	if (sock->hasPendingDatagrams()) {
		if (main) emit sgRxMain();
		if (aux) emit sgRxAux();
	}

	int size = 0;

	bool enabled = false;
	if (main) enabled = sets.main;
	if (aux) enabled = sets.aux;

	while (sock->hasPendingDatagrams() && run && enabled) {
		size = sock->pendingDatagramSize();
		convertor->setBufSize(size);
		sock->readDatagram(convertor->getBuf(), size);

		if (convertor->convert()) emit sgWr();
		else emit sgNoWr();

		if (main) timerRxMain->start();
		if (aux) timerRxAux->start();
	}
}
Beispiel #5
0
void ICServer::processPendingDatagrams()
{
    QByteArray datagram;
    QUdpSocket *socket = isRunning ? udpSocket : testUdpSocket;

    do {
        QHostAddress *address = new QHostAddress;
        datagram.resize(socket->pendingDatagramSize());
        socket->readDatagram(datagram.data(), datagram.size(), address);

        ICMessageHandler *messageHandler = new ICMessageHandler(this);
        connect(messageHandler, SIGNAL(connectionOffer(QString)), this, SLOT(processSidCollision(QString)));
        connect(messageHandler, SIGNAL(serverDiscovery(QHostAddress,QString)), this, SLOT(processDiscovery(QHostAddress,QString)));
        connect(messageHandler, SIGNAL(questionRequest(QHostAddress)), this, SLOT(processRequest(QHostAddress)));
        connect(messageHandler, SIGNAL(answerReady(ICAnswer,QString)), this, SLOT(processAnswer(ICAnswer,QString)));

        ICMessageProcessor *processor = new ICMessageProcessor(messageHandler, *address, datagram);

        QThreadPool::globalInstance()->start(processor);

        qDebug()<< "[1] Received from " << *address << datagram;

        delete address;
    } while (socket->hasPendingDatagrams());
}
void AudioReceiver::readPendingAudioRcvrData() {

    QUdpSocket *socket = qobject_cast<QUdpSocket *>(sender());

    while (socket->hasPendingDatagrams()) {

        m_datagram.resize(socket->pendingDatagramSize());

        if (socket->readDatagram(m_datagram.data(), m_datagram.size()) < 0) {

            AUDIO_RECEIVER << "read client" << m_client << "socket failed.";
            if (io->rcveIQ_toggle) {  // toggles the rcveIQ signal

                emit rcveIQEvent(this, 2);
                io->rcveIQ_toggle = false;
            }
        }
        else {

            io->au_queue.enqueue(m_datagram);

            if (!io->rcveIQ_toggle) {  // toggles the rcveIQ signal

                emit rcveIQEvent(this, 1);
                io->rcveIQ_toggle = true;
            }
        }
    }
}
Beispiel #7
0
void MainWindow::controlMessageReceived() {
    qDebug() << "message received";
    QUdpSocket* udpSocket = qobject_cast<QUdpSocket*>(sender());
    while (udpSocket->hasPendingDatagrams()) {
             QByteArray datagram;
             datagram.resize(udpSocket->pendingDatagramSize());
             QHostAddress sender;
             quint16 senderPort;

             udpSocket->readDatagram(datagram.data(), datagram.size(),
                                     &sender, &senderPort);
             if (datagram=="left") {
                 drone->moveLeft();
             } else if (datagram== "right") {
                 drone->moveRight();
             } else if (datagram=="stayx" && datagram=="stayy"){
                 drone->stay();
             } else if (datagram=="up") {
                 drone->higher();
             } else if (datagram=="down") {
                 drone->lower();
             } else {
                 qDebug() << "invalid command received";
             }
         }

}
Beispiel #8
0
void OceanSocket::processIncomingWaves()
{
    QUdpSocket* socket = dynamic_cast<QUdpSocket*>(QObject::sender());
    while (socket->hasPendingDatagrams())
    {
        QByteArray wave;
        QHostAddress host;
        wave.resize(socket->pendingDatagramSize());
        socket->readDatagram(wave.data(), wave.size(), &host);
        for (int i = 0; i < boundAddresses.count(); i++) {
            if (host == boundAddresses.at(i))
                // skip processing since this is our own packet
                return;
        }
        if (wave.startsWith(NET_OCEAN_HEARTBEAT))
            emit shipHeartbeat(host, wave.mid(1).data());
        else if (wave.startsWith(NET_OCEAN_COURSE_CHANGE))
            emit shipChangedCourse(host, wave.mid(1).data());
        else if (wave.startsWith(NET_OCEAN_RETURN_TO_PORT))
            emit shipDocked(host, wave.mid(1).data());
        else if (wave.startsWith(NET_OCEAN_ADMIN_LOCK_REQ))
            emit adminLockRequested(host, wave.mid(1).data());
        else if (wave.startsWith(NET_OCEAN_ADMIN_LOCK_RESP))
            emit adminLockRequestReponse(host, (atoi(wave.mid(1,1).data()) == NET_OCEAN_ACKNOWLEDGE), wave.mid(2).data());
        else if (wave.startsWith(NET_OCEAN_MESSAGE))
            this->processMessage(host, wave.mid(1).data());
        else if (wave.startsWith(NET_OCEAN_SAIL))
            emit shipSailed(host, wave.mid(1).data());
    }
}
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();
    }
}
Beispiel #10
0
void StunClient::onStunReadyRead()
{
    QUdpSocket *sock = (QUdpSocket*)(sender());
    qDebug()<<""<<sock;

    u08bits rbuf[STUN_BUFFER_SIZE];

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

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

        {
            m_sending_udp = false;
            m_sending_timer->stop();
        }

        qDebug()<<"read: "<<sender<<senderPort<<datagram.length()<<datagram.toHex().left(20)<<"...";
        
        for (int i = 0; i < datagram.length(); i ++) {
            char c = datagram.at(i);
            fprintf(stderr, "%c", isprint(c) ? c : '.');
            if (i > 375) break;
        }
        fprintf(stderr, " ...]\n");

        this->processResponse(datagram, QString("%1:%2").arg(sender.toString()).arg(senderPort));
        // processTheDatagram(datagram);
    }
}
Beispiel #11
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]));
    }
}
Beispiel #12
0
void TestClient::testSendKeyInputPacket(){
	Client* client = new Client(NULL);

	QUdpSocket* socket = new QUdpSocket();
	socket->bind(INCOMING_PORT);

	client->setDirection(1);
	client->setIsJumping(false);
	client->setIsLaunching(true);
	client->sendDatagram(KEY_INPUT_PACKET);

	QHostAddress *address = NULL;
	quint16 *port = NULL;
	QByteArray *datagram = new QByteArray(socket->pendingDatagramSize(), (char) 0);

	socket->readDatagram(datagram->data(), datagram->size(), address, port);

	QCOMPARE(datagram->at(0), KEY_INPUT_PACKET);
	QCOMPARE((int)datagram->at(1), -1);
	QCOMPARE((int)datagram->at(2), 1);
	QCOMPARE((bool)datagram->at(3), false);
	QCOMPARE((bool)datagram->at(4), true);

	delete socket;
}
Beispiel #13
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);
}
void SocketTestWindow::readyReadMessage()
{
    if(m_tcpEnable)
    {
        QByteArray data = m_socketClient->readAll();
        QString rd = data;
//        char logbuf[BUFSIZ] = {0};
//        sprintf(logbuf,"receive data from %s:%d  %s",)
//        QLogProvider::getLog()->log(logbuf);
        ui->m_teRecvData->setText(rd);

    }
    else
    {
        QUdpSocket* udpSocket = dynamic_cast<QUdpSocket*>(m_socketClient);
        while (udpSocket->hasPendingDatagrams()) {
                 QByteArray datagram;
                 datagram.resize(udpSocket->pendingDatagramSize());
                 udpSocket->readDatagram(datagram.data(), datagram.size(),
                                         &m_remoteHost, &m_remotePort);
                 char logbuf[BUFSIZ] = {0};
                 sprintf(logbuf,"receive datagram from %s:%d",m_remoteHost.toString().toStdString().c_str(),m_remotePort);
                 ui->m_teRecvData->setText(datagram);
                 QLogProvider::getLog()->log(logbuf);
        }
    }
}
Beispiel #15
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);
    }
}
Beispiel #16
0
void tst_QUdpSocket::ipv6Loop()
{
    QFETCH(QByteArray, peterMessage);
    QFETCH(QByteArray, paulMessage);
    QFETCH(bool, success);

    QUdpSocket peter;
    QUdpSocket paul;

    quint16 peterPort = 28124;
    quint16 paulPort = 28123;

    if (!peter.bind(QHostAddress::LocalHostIPv6, peterPort)) {
        QCOMPARE(peter.error(), QUdpSocket::UnsupportedSocketOperationError);
    } else {
        QVERIFY(paul.bind(QHostAddress::LocalHostIPv6, paulPort));

        QCOMPARE(peter.writeDatagram(peterMessage.data(), peterMessage.length(), QHostAddress("::1"),
                                     paulPort), qint64(peterMessage.length()));
        QCOMPARE(paul.writeDatagram(paulMessage.data(), paulMessage.length(),
                                    QHostAddress("::1"), peterPort), qint64(paulMessage.length()));

        char peterBuffer[16*1024];
        char paulBuffer[16*1024];
#if !defined(Q_OS_WINCE)
        QVERIFY(peter.waitForReadyRead(5000));
        QVERIFY(paul.waitForReadyRead(5000));
#else
        QVERIFY(peter.waitForReadyRead(15000));
        QVERIFY(paul.waitForReadyRead(15000));
#endif
        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);
    }
}
Beispiel #17
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());
        }
    }
}
Beispiel #18
0
void CNetwork::DataMayRead( )
{
    QByteArray byData;
    QUdpSocket* udpServer = qobject_cast< QUdpSocket* > ( sender( ) );

    while ( udpServer->hasPendingDatagrams( ) ) {
        byData.resize( udpServer->pendingDatagramSize( ) );
        udpServer->readDatagram( byData.data( ), byData.size( ) );
        ProcessData( byData );
    }
}
Beispiel #19
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);
}
Beispiel #20
0
/**
  * @return A null header if error.
  */
Common::MessageHeader UDPListener::readDatagramToBuffer(QUdpSocket& socket, QHostAddress& peerAddress)
{
   quint16 port;
   const qint64 datagramSize = socket.readDatagram(this->buffer, BUFFER_SIZE, &peerAddress, &port);
   if (datagramSize == -1)
   {
      L_WARN(QString("UDPListener::readDatagramToBuffer(..): Unable to read multicast datagram from address:port: %1:%2").arg(peerAddress.toString()).arg(port));
      return Common::MessageHeader();
   }

   Common::MessageHeader header = Common::MessageHeader::readHeader(buffer);

   if (header.getSize() > datagramSize - Common::MessageHeader::HEADER_SIZE)
   {
      L_ERRO("The message size (header.size) exceeds the datagram size received");
      header.setNull();
      return header;
   }

   if (header.getSenderID() == this->peerManager->getSelf()->getID())
   {
      // L_WARN("We receive a datagram from ourself, skip"); // Don't care . . .
      header.setNull();
      return header;
   }

   if (header.getType() != Common::MessageHeader::CORE_IM_ALIVE)
   {
      PM::IPeer* peer = this->peerManager->getPeer(header.getSenderID());
      if (!peer)
      {
          L_WARN(QString("We receive a datagram from an unknown peer (%1), skip").arg(peerAddress.toString()));
         header.setNull();
         return header;
      }

      if (!peer->isAlive())
      {
          L_WARN(QString("We receive a datagram from a dead peer (%1), skip").arg(peerAddress.toString()));
         header.setNull();
         return header;
      }

      L_DEBU(QString("Receive a datagram UDP from %1, %2").arg(peer->toStringLog()).arg(header.toStr()));
   }
   else
   {
      L_DEBU(QString("Receive a datagram UDP from %1, %2").arg(header.getSenderID().toStr()).arg(header.toStr()));
   }
   return header;
}
void StreamDataChunker::next(QIODevice* device)
{
    qDebug() << "StreamDataChunker::next() [" << chunkCounter_++ << "]";

    QUdpSocket* socket = static_cast<QUdpSocket*>(device);
    bytesRead_ = 0;

    // Get writable buffer space for chunk.
    pelican::WritableData chunk = getDataStorage(chunkSize_);
    if (chunk.isValid())
    {
        // Get pointer to start of chunk memory.
        char* ptr = (char*)chunk.ptr();

        // Read datagrams for chunk from the socket.
        while (isActive() && bytesRead_ < chunkSize_)
        {
            // Read the datagram, but avoid using pendingDatagramSize()
            if (!socket->hasPendingDatagrams())
            {
                // MUST wait for the next datagram
                socket->waitForReadyRead(100);
                continue;
            }
            qint64 maxlength = chunkSize_ - bytesRead_;
            qint64 length = socket->readDatagram(ptr + bytesRead_, maxlength);
            if (length > 0)
                bytesRead_ += length;
        }
    }

    // Discard the datagram if there is no space.
    else
    {
        socket->readDatagram(0, 0);
    }
}
Beispiel #22
0
void ReceiveNetworkPackets() { //waits for the LabView kill string, which indicates that LabView is done using the odroid and that the odroid should shutdown (managed in an upper level shell script which both executes this program and then shuts down the odroid after this program finishes/ends.
    const unsigned short datagramsize=LabViewKillString.size();
    QUdpSocket udpSocket; udpSocket.bind(HostPortNumber); //binds to HostPortNumber
    QByteArray datagram; datagram.resize(datagramsize);
    string str=" "; //Intermediate String for Later String Comparison
    while(!EndProgram) {
        if (!IsFindSquaresBusy) {
            udpSocket.readDatagram(datagram.data(), datagramsize);
            str=datagram.data();
            if(str==LabViewKillString) {EndProgram=true;}
            else usleep(ReceivePacketsDelay);
        }
        else usleep(FindSquares_Period); //So, basically, this thread will read UDP packets when FindSquares is not running and will do nothing except sleep when it is running to maximize the multithreading part of that algoritm. It waits as long as FindSquares takes to execute.
    }
    cout<<"DONE! Received LabView KillString! \n"; //Just a little dialog to know that it received the LabView killstring and that was why it shut down.
}
void UdpRelay::onClientUdpSocketReadyRead()
{
    QUdpSocket *sock = qobject_cast<QUdpSocket *>(sender());
    if (!sock) {
        emit info("Fatal. A false object calling onClientUdpSocketReadyRead.");
        return;
    }

    if (sock->pendingDatagramSize() > RecvSize) {
        emit info("[UDP] Datagram is too large. Discarded.");
        return;
    }

    QByteArray data;
    data.resize(sock->pendingDatagramSize());
    QHostAddress r_addr;
    quint16 r_port;
    sock->readDatagram(data.data(), RecvSize, &r_addr, &r_port);

    QByteArray response;
    if (isLocal) {
        data = encryptor->decryptAll(data);
        Address destAddr;
        int header_length = 0;
        bool _auth;

        Common::parseHeader(data, destAddr, header_length, _auth);
        if (header_length == 0) {
            emit info("[UDP] Can't parse header. "
                      "Wrong encryption method or password?");
            return;
        }
        response = QByteArray(3, static_cast<char>(0)) + data;
    } else {
        data.prepend(Common::packAddress(r_addr, r_port));
        response = encryptor->encryptAll(data);
    }

    Address clientAddress = cache.key(sock);
    if (clientAddress.getPort() != 0) {
        listenSocket.writeDatagram(response,
                                   clientAddress.getFirstIP(),
                                   clientAddress.getPort());
    } else {
        emit debug("[UDP] Drop a packet from somewhere else we know.");
    }
}
Beispiel #24
0
void ServerPool::newUdpDatagram(void)
{
    QUdpSocket *socket = dynamic_cast<QUdpSocket*>(sender());

    while (socket->state() == QAbstractSocket::BoundState &&
           socket->hasPendingDatagrams())
    {
        QByteArray buffer;
        buffer.resize(socket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;

        socket->readDatagram(buffer.data(), buffer.size(),
                             &sender, &senderPort);
        emit newDatagram(buffer, sender, senderPort);
    }
}
Beispiel #25
0
void ServerSktUdp::newData()
{
	QUdpSocket* s = qobject_cast<QUdpSocket*>(sender());
	if (!s) return;

	qint64 bufLen = s->pendingDatagramSize();
	char* buf = TK::createBuffer(bufLen, MAXBUFFER);
	if (!buf) return;

	QHostAddress addr; quint16 port(0);

	qint64 readLen = 0;
	qint64 ioLen = s->readDatagram(buf, bufLen, &addr, &port);

	//while (ioLen > 0)
	//{
		readLen += ioLen;
	//	ioLen = s->readDatagram(buf+readLen, bufLen-readLen, &addr, &port);
	//}

	if (ioLen >= 0)
	{
		Conn* conn = (Conn*)getCookie(TK::ipstr(addr, port, false));
		if (!conn)
		{
			conn = new Conn;
			if (conn)
			{
				conn->key  = TK::ipstr(addr, port, false);
				conn->addr = addr;
				conn->port = port;
				setCookie(conn->key, conn);
			}
		}

		if (conn)
		{
			recordRecv(readLen);

			conn->stamp = QDateTime::currentDateTime();
			dump(buf, readLen, false, conn->key);
		}
	}

	TK::releaseBuffer(buf);
}
Beispiel #26
0
/**
  * @return A null header if error.
  */
Common::MessageHeader UDPListener::readDatagramToBuffer(QUdpSocket& socket, QHostAddress& peerAddress)
{
   qint64 datagramSize = socket.readDatagram(this->buffer, BUFFER_SIZE, &peerAddress);

   Common::MessageHeader header = Common::MessageHeader::readHeader(buffer);

   if (header.getSize() > datagramSize - Common::MessageHeader::HEADER_SIZE)
   {
      L_ERRO("header.getSize() > datagramSize");
      header.setNull();
      return header;
   }

   if (header.getSenderID() == this->peerManager->getID())
   {
      // L_WARN("We receive a datagram from ourself, skip"); // Don't care..
      header.setNull();
      return header;
   }

   if (header.getType() != Common::MessageHeader::CORE_IM_ALIVE)
   {
      PM::IPeer* peer = this->peerManager->getPeer(header.getSenderID());
      if (!peer)
      {
         L_WARN("We receive a datagram from an unknown peer, skip");
         header.setNull();
         return header;
      }

      if (!peer->isAlive())
      {
         L_WARN("We receive a datagram from a dead peer, skip");
         header.setNull();
         return header;
      }

      L_DEBU(QString("Receive a datagram UDP from %1, %2").arg(peer->toStringLog()).arg(header.toStr()));
   }
   else
   {
      L_DEBU(QString("Receive a datagram UDP from %1, %2").arg(header.getSenderID().toStr()).arg(header.toStr()));
   }
   return header;
}
Beispiel #27
0
void tst_QUdpSocket::writeToNonExistingPeer()
{
    QSKIP("Connected-mode UDP sockets and their behaviour are erratic", SkipAll);
    QFETCH(QHostAddress, peerAddress);
    quint16 peerPort = 34534;
    qRegisterMetaType<QAbstractSocket::SocketError>("QAbstractSocket::SocketError");

    QUdpSocket sConnected;
    QSignalSpy sConnectedReadyReadSpy(&sConnected, SIGNAL(readyRead()));
    QSignalSpy sConnectedErrorSpy(&sConnected, SIGNAL(error(QAbstractSocket::SocketError)));
    sConnected.connectToHost(peerAddress, peerPort, QIODevice::ReadWrite);

    // the first write succeeds...
    QCOMPARE(sConnected.write("", 1), qint64(1));

    // the second one should fail!
    QTest::qSleep(1000);                   // do not process events
    QCOMPARE(sConnected.write("", 1), qint64(-1));
    QCOMPARE(int(sConnected.error()), int(QUdpSocket::ConnectionRefusedError));

    // the third one will succeed...
    QCOMPARE(sConnected.write("", 1), qint64(1));
    QTestEventLoop::instance().enterLoop(1);
    QCOMPARE(sConnectedReadyReadSpy.count(), 0);
    QCOMPARE(sConnectedErrorSpy.count(), 1);
    QCOMPARE(int(sConnected.error()), int(QUdpSocket::ConnectionRefusedError));

    // we should now get a read error
    QCOMPARE(sConnected.write("", 1), qint64(1));
    QTest::qSleep(1000);                   // do not process events
    char buf[2];
    QVERIFY(!sConnected.hasPendingDatagrams());
    QCOMPARE(sConnected.bytesAvailable(), Q_INT64_C(0));
    QCOMPARE(sConnected.pendingDatagramSize(), Q_INT64_C(-1));
    QCOMPARE(sConnected.readDatagram(buf, 2), Q_INT64_C(-1));
    QCOMPARE(int(sConnected.error()), int(QUdpSocket::ConnectionRefusedError));

    QCOMPARE(sConnected.write("", 1), qint64(1));
    QTest::qSleep(1000);                   // do not process events
    QCOMPARE(sConnected.read(buf, 2), Q_INT64_C(0));
    QCOMPARE(int(sConnected.error()), int(QUdpSocket::ConnectionRefusedError));

    // we should still be connected
    QCOMPARE(int(sConnected.state()), int(QUdpSocket::ConnectedState));
}
void IoInterface::recvMessage()
{
    //qDebug() << "recvMessage()";
    QString t;
    t.sprintf("first Attr : %x", CeBuffer->firstAttr);
    //qDebug() << t;

    if(CeBuffer->socket->pendingDatagramSize() > 0)
    {
        QByteArray buffer(CeBuffer->socket->pendingDatagramSize(), 0);

        QObject *sender = const_cast<QObject*>(QObject::sender());
        QUdpSocket *sock = static_cast<QUdpSocket*>(sender);
        sock->readDatagram(buffer.data(), buffer.size());

        //printMessageInfo(buffer);

        if(getOperationTypeFromMessage(buffer) == 0xc0)
        {
            switch(getOperationFromMessage(buffer))
            {
                case 0x01:
                CeBuffer->firstAttr = getOperandFromMessage(buffer);
                break;
                case 0x02:
                CeBuffer->secondAttr = getOperandFromMessage(buffer);
                break;
                case 0x03:
                CeBuffer->thirdAttr = getOperandFromMessage(buffer);
                break;
                default:
                break;
            }
        }

        printCEInfo(*CeBuffer);

        emit initCompleteCeStructSignal();

    }

}
Beispiel #29
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));
    }
}
Beispiel #30
0
void TestClient::testSendHelloPacket(){

	Client* client = new Client(NULL);

	QUdpSocket* socket = new QUdpSocket();
	socket->bind(INCOMING_PORT);

	client->sendDatagram(HELLO_PACKET);

	QHostAddress *address = NULL;
	quint16 *port = NULL;
	QByteArray *datagram = new QByteArray(socket->pendingDatagramSize(), (char) 0);

	socket->readDatagram(datagram->data(), datagram->size(), address, port);

	QCOMPARE(datagram->at(0), HELLO_PACKET);

	delete socket;

}