void FetchThread::process(QString phost)
{

    QUdpSocket *udpSocket ;
    udpSocket= new QUdpSocket(0);
    udpSocket->bind(QHostAddress::LocalHost, 9999);
    udpSocket->waitForConnected(250);



    QTcpSocket socket;
    socket.connectToHost("localhost", 4949);
    socket.waitForConnected(500);

    while (socket.waitForReadyRead(250));
    QString t_hello = socket.readAll();
    qDebug() << "READ: " << t_hello;

    socket.write(QString("list\n").toStdString().c_str() );
    while (socket.waitForReadyRead(250));
    QString buf1 = socket.readAll();

    qDebug() << "READ: " << buf1;
    QStringList list_probe = buf1.split(QRegExp("\\s+"));

    for (int z=0; z< list_probe.size(); z++)
    {
        QString probe=list_probe.at(z);
        QString cmd = QString("fetch ").append(probe).append("\n");
        qDebug() << "cmd : " << cmd;
        socket.write(cmd.toStdString().c_str() );


        while (socket.waitForReadyRead(250));
        QString buf2 = socket.readAll();
        qDebug() << "Rep fetch :" << buf2 << "\n";

        QRegularExpression re("(\\w+).(\\w+) ([0-9.]+)\\n");
        QRegularExpressionMatchIterator i = re.globalMatch(buf2);
        re.setPatternOptions(QRegularExpression::MultilineOption);

        while (i.hasNext()) {
            QRegularExpressionMatch match = i.next();
            QString s_metric = match.captured(1);
            QString s_value = match.captured(3);
            QString s_mtr = "monit2influxdb,metric="+probe + "_" + s_metric + ",host=" + phost+ " value=" + s_value + " " + QString::number(1000000* QDateTime::currentMSecsSinceEpoch());
            qDebug() << "metric:  " << s_mtr.toLower();

            udpSocket->writeDatagram(s_mtr.toStdString().c_str(), QHostAddress::LocalHost, 9999);




        }

        udpSocket->close();


    }
}
Beispiel #2
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 #3
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());
}
Beispiel #4
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 #5
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]));
    }
}
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 #7
0
void LinkQuality::send()
{

    cout<<"send"<<endl;
    int size = packetLengthEdit->text().toInt();
    int count = countEdit->text().toInt();

    //write message to log file
    gpsLock.lockForRead();
    fileLock.lockForWrite();
    *logFile<<"*********************************************"<<endl;
    *logFile<<"local:"<<endl<<"  "<<this->time.toAscii()<<"  "<<this->longitude.toAscii()<<"  "<<latitude.toAscii()
           <<"   "<<count<<"   "<<size<<endl;
    fileLock.unlock();
    gpsLock.unlock();

    QByteArray datagram;
    QDataStream out(&datagram, QIODevice::WriteOnly);
    out<<qint16(1);
    datagram.resize(size);
    cout<<datagram.size()<<endl;
    QUdpSocket sendSocket;
    for(int i = 0; i < count; i++)
    {
        sendSocket.writeDatagram(datagram, datagram.size(), QHostAddress(remoteAddr), CMD_PORT);
        //sleep(1);
    }
}
// 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);
    }
}
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;
            }
        }
    }
}
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 #11
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());
    }
}
Beispiel #12
0
OceanSocket::OceanSocket(QObject *parent) :
    QObject(parent)
{
    // setup the heartbeat timer
    heartbeat = new QTimer(this);
    connect(heartbeat, SIGNAL(timeout()), this, SLOT(heartbeatTimer()));

    // setup our ocean sockets
    groupAddress = QHostAddress(MULTICAST_ADDRESS);

    QList<QNetworkInterface> ifaces = QNetworkInterface::allInterfaces();
    for (int i = 0; i < ifaces.count(); i++) {
        QNetworkInterface iface = ifaces.at(i);
        if (iface.flags().testFlag(QNetworkInterface::IsUp) && !iface.flags().testFlag(QNetworkInterface::IsLoopBack) && iface.flags().testFlag(QNetworkInterface::CanMulticast)) {
            for (int j = 0; j < iface.addressEntries().count(); j++) {
                if (iface.addressEntries().at(j).ip().protocol() != QAbstractSocket::IPv4Protocol) continue;
                qDebug() << "Ocean bind to iface: " << iface.name() << endl << "IP: " << iface.addressEntries().at(j).ip().toString() << endl;
                QUdpSocket* socket = new QUdpSocket(this);
                socket->bind(QHostAddress::AnyIPv4, 8047, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint);
                socket->joinMulticastGroup(groupAddress, iface);
                connect(socket, SIGNAL(readyRead()), this, SLOT(processIncomingWaves()));
                boundAddresses.append(iface.addressEntries().at(j).ip());
                multicastSockets.append(socket);
            }
        }
    }

    sendSocket = new QUdpSocket(this);
    sendSocket->bind();
}
Beispiel #13
0
/*
 * 析构时发送"我离开了"的消息
 * 因为进行到窗口的析构函数时,子对象都已经被删除,故而不能使用_sender成员进行发送
*/
ChatWindow::~ChatWindow()
{
    QUdpSocket tmpSocket;
    QByteArray bytes=pack_Leave(_username,getIPv4());
    tmpSocket.writeDatagram(bytes,bytes.length(),QHostAddress::Broadcast,_port);
    delete ui;
}
Beispiel #14
0
void QDmxE131Controler::readDatagram()
{
    if(sender())
    {
        QUdpSocket* socket = qobject_cast<QUdpSocket*>(sender());
        if(socket)
        {
            while(socket->hasPendingDatagrams())
            {
                QNetworkDatagram datagram = socket->receiveDatagram();
                if(datagram.senderAddress().isInSubnet(_address, _entry.prefixLength()))
                {
                    QByteArray rawData = datagram.data();

                    if(_packetizer->checkPacket(rawData))
                    {
                        QByteArray dmx;
                        quint32 u;
                        _packetizer->fillDMXdata(rawData, dmx, u);
                        u--;

                        if(_listenedUniverse.contains(u))
                            emit hasDmx(u, dmx);
                    }
                }
            }
        }
    }
}
Beispiel #15
0
void ArduinoThread::run() {
    serv = new QTcpServer(this);
    connect(serv, SIGNAL(newConnection()), this, SLOT(NewConnection()));

    serv->listen(QHostAddress::Any, 34543);

    QProcess proc;
    proc.start("/sbin/ifconfig");
    proc.waitForFinished();
    QString ifconfigOutput = proc.readAllStandardOutput();

    QString strAddress;
    QRegExp rx("addr:([^ ]+)");
    int offset = 0;
    while(-1 != (rx.indexIn(ifconfigOutput, offset))) {
        offset += rx.matchedLength();

        strAddress = "[" + rx.cap(1) + "]";

        if(strAddress == "[127.0.0.1]")
            continue;
        if(!strAddress.contains(QRegExp("\\[\\d+\\.\\d+\\.\\d+\\.\\d+\\]")))
            continue;

        break;
    }

    QUdpSocket *udpSocket = new QUdpSocket(this);
    udpSocket->writeDatagram(strAddress.toAscii(), QHostAddress::Broadcast, 12345);

    exec();
}
Beispiel #16
0
void RacomClient::onRawSIDataUdpSocketReadyRead()
{
	if(status() != Status::Running)
		return;
#if (QT_VERSION >= QT_VERSION_CHECK(5, 8, 0))
	QUdpSocket *sock = rawDataUdpSocket();
	QNetworkDatagram dg = sock->receiveDatagram();
	QByteArray data = dg.data();
	qfInfo() << data.toHex();
	// remove possible initial garbage
	int i = 0;
	for(i=0; i<data.size(); i++)
		if(data.at(i) == 0x02)
			break;
	data = data.mid(i);
	// remove possible multiple 0x02
	for(i=1; i<data.size(); i++)
		if(data.at(i) != 0x02)
			break;
	data = data.mid(i-1);
	qfInfo() << "stripped data:" << data.toHex();
	CardReader::CardReaderPlugin *plugin = cardReaderPlugin();
	if(plugin) {
		if(!m_siDriver) {
			m_siDriver = new siut::DeviceDriver(this);
			connect(m_siDriver, &siut::DeviceDriver::siTaskFinished, plugin, &CardReader::CardReaderPlugin::emitSiTaskFinished);
		}
		m_siDriver->processData(data);
	}
#else
	qfWarning() << "Racom client is not supported with Qt < 5.8";
#endif
}
Beispiel #17
0
void ClientSktUdp::newData()
{
    QUdpSocket* s = qobject_cast<QUdpSocket*>(sender());
    if (!s) return;

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

    qint64 readLen = 0;
    qint64 ioLen = s->read(buf, bufLen);

    while (ioLen > 0)
    {
        readLen += ioLen;
        ioLen = s->read(buf+readLen, bufLen-readLen);
    }

    if (ioLen >= 0)
    {
        recordRecv(readLen);
        dump(buf, readLen, false);
    }

    TK::releaseBuffer(buf);
}
Beispiel #18
0
void RacomClient::onUdpSocketReadyRead()
{
	if(status() != Status::Running)
		return;
	QUdpSocket *sock = udpSocket();
	QNetworkDatagram dg = sock->receiveDatagram();
	QByteArray data = dg.data();
	qfInfo() << data.toHex();
	// remove possible initial garbage
	int i = 0;
	for(i=0; i<data.size(); i++)
		if(data.at(i) == 0x02)
			break;
	data = data.mid(i);
	// remove possible multiple 0x02
	for(i=1; i<data.size(); i++)
		if(data.at(i) != 0x02)
			break;
	data = data.mid(i-1);
	qfInfo() << "stripped data:" << data.toHex();
	if(!m_siDriver) {
		m_siDriver = new siut::DeviceDriver(this);
		CardReader::CardReaderPlugin *plugin = cardReaderPlugin();
		if(plugin) {
			connect(m_siDriver, &siut::DeviceDriver::messageReady, plugin, &CardReader::CardReaderPlugin::emitSiMessagereceived);
		}
	}
	m_siDriver->processSiPacket(data);
}
Beispiel #19
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);
    }
}
void SocketTestWindow::on_m_pbSend_clicked()
{
    QString data = ui->m_teSendData->toPlainText();
    if(data.length() == 0)
    {
        return  ;
    }
    QByteArray array;
    array.append(data);
    if(m_isServer)
    {
       m_socketBase->sendData(array);
    }
    else
    {
        if(m_tcpEnable)
        {
            if(m_socketClient)
                m_socketClient->write(array);
        }
        else
        {
            QUdpSocket* udpSocket = dynamic_cast<QUdpSocket*>(m_socketClient);
            if(udpSocket)
                udpSocket->write(array);
        }

    }


}
bool RemoteInterfaceSender::sendMessage(RemoteInterfaceMessage* message) {
	// Do we have a valid destination?
	if(message && message->destinationIp != "" && message->destinationPort != 0) {

		// Init socket
		QUdpSocket socket;
		if(!socket.bind(QHostAddress(server->ip), server->port, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint)) {
			// Show error
			Debug::error("[RemoteInterfaceSender] could not bind");
			return false;
		} else {
			// Add port and ip keys
			if(socket.localAddress().toString() != server->ip) 	message->properties->insert("reply-ip",socket.localAddress().toString());
			if(socket.localPort() != server->port) 				message->properties->insert("reply-port",QString("%1").arg(socket.localPort()));

			// Write to socket
			socket.writeDatagram(message->toString().toAscii(), QHostAddress(message->destinationIp), message->destinationPort);

			// Add to sent list
			server->addMessageToSent(message);

			// Show what happened
			Debug::print("[RemoteInterfaceSender] sent %1 message to %2:%3", message->type, message->destinationIp, message->destinationPort);
			return true;
		}

	} else {
		// Show error
		Debug::warning("[RemoteInterfaceSender] message destination must be specified!");
		return false;
	}
}
Beispiel #22
0
void ClientSktUdp::error()
{
    QUdpSocket* s = qobject_cast<QUdpSocket*>(sender());

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

    unplug();
}
Beispiel #23
0
/**
 * @brief TransmitterTask::run
 */
void TransmitterTask::run()
{
    QUdpSocket socket;
    socket.bind(port, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint);
    socket.writeDatagram(data, address, port);
    socket.waitForBytesWritten();
    socket.close();
    qDebug() << "Task:" << address << ':' << port << "<-" << data;
}
Beispiel #24
0
QUdpSocket *KSocketFactory::datagramSocket(const QString &protocol, const QString &host, QObject *parent)
{
    QUdpSocket *socket = new QUdpSocket(parent);
#ifndef QT_NO_NETWORKPROXY
    // ### do something else?
    socket->setProxy(proxyForDatagram(protocol, host));
#endif
    return socket;
}
// Creates a suitable device ready for reading.
QIODevice* JTestChunker::newDevice()
{
    // Return an opened QUdpSocket.
    QUdpSocket* socket = new QUdpSocket;
    socket->bind(QHostAddress(host()), port());

    // Wait for the socket to bind.
    while (socket->state() != QUdpSocket::BoundState) {}
    return socket;
}
Beispiel #26
0
void DevicePluginWakeOnLan::wakeup(QString mac)
{
    const char header[] = {char(0xff), char(0xff), char(0xff), char(0xff), char(0xff), char(0xff)};
    QByteArray packet = QByteArray::fromRawData(header, sizeof(header));
    for(int i = 0; i < 16; ++i) {
        packet.append(QByteArray::fromHex(mac.remove(':').toLocal8Bit()));
    }
    qCDebug(dcWakeOnLan) << "Created magic packet:" << packet.toHex();
    QUdpSocket udpSocket;
    udpSocket.writeDatagram(packet.data(), packet.size(), QHostAddress::Broadcast, 9);
}
Beispiel #27
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 );
    }
}
void UdpRelay::onClientDisconnected()
{
    QUdpSocket *client = qobject_cast<QUdpSocket *>(sender());
    if (!client) {
        emit info("Fatal. A false object calling onClientDisconnected.");
        return;
    }
    cache.remove(cache.key(client));
    client->deleteLater();
    emit debug("[UDP] A client connection is disconnected and destroyed.");
}
/**
 * @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;
}
Beispiel #30
-1
void SendNetworkPackets(unsigned int i, unsigned int j, unsigned int k) { //sends desired data over UDP to the robot. I used it to send the # of squares and the ms required to render each frame. (It uses the time data to know when to read for UDP packets and hence the for loop iteration essentially stands for the # of frames it wants to read from the odroid.
    static QUdpSocket udpSocket; //create socket
    
    QByteArray datagram = QByteArray::number(i) + " " + QByteArray::number(j) + " " + QByteArray::number(k) + " "; //create data stream
    
    udpSocket.writeDatagram(datagram.data(), datagram.size(), QHostAddress(QstringTargetIPAddress), TargetPortNumber); //send that data stream over UDP to the TargetIpAddress with the given TargetPortNumber
}