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();
    }
}
Example #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]));
    }
}
Example #3
0
void TimeSync::getNTPTime()
{
    QUdpSocket sock;
    sock.connectToHost("0.pool.ntp.org",123);
    if(!sock.waitForConnected(1000))return;
    QByteArray data(48,char(0)); *(reinterpret_cast<qint32 *>(&data.data()[0]))=4194959577;
    if(sock.write(data)<0||!sock.waitForReadyRead(3000)||sock.bytesAvailable()!=48)return;
    data=sock.readAll();
    quint32 seconds=qToBigEndian(*(reinterpret_cast<quint32 *>(&data.data()[40])));
    quint32 fraction=qToBigEndian(*(reinterpret_cast<quint32 *>(&data.data()[44])));
    quint32 newTime=QDateTime::fromMSecsSinceEpoch(seconds*1000ll+fraction*1000ll/0x100000000ll-2208988800000ll).toTime_t();

    if(newTime<1451606400 || newTime>4000000000){
        QThread::msleep(500);
        emit startSync();
        return;
    }
    qint32 tempTimeShift=qint64(newTime)-qint64(QDateTime::currentDateTime().toTime_t());

    if(timeShift!=0)tempTimeShift=qint32((qint64(timeShift)+qint64(tempTimeShift))/2);

    if(tempTimeShift>3600 || tempTimeShift<-3600){
        static bool showMessage=true;
        if(showMessage)emit warningMessage(julyTr("TIME_SYNC_ERROR","Your clock is not set. Please close the Qt Bitcoin Trader and set the clock. Changing time at Qt Bitcoin Trader enabled can cause errors and damage the keys."));
        showMessage=false;
    }
    else
        timeShift.fetchAndStoreOrdered(tempTimeShift);

    getNTPTimeRetryCount++;
    if(getNTPTimeRetryCount<3)emit startSync();
}
Example #4
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 "";
}
Example #5
0
// 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);
    }
}
Example #6
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);
    }
}
Example #7
0
void tst_QUdpSocket::zeroLengthDatagram()
{
    QFETCH_GLOBAL(bool, setProxy);
    if (setProxy)
        return;

    QUdpSocket receiver;
    QVERIFY(receiver.bind());

    QVERIFY(!receiver.waitForReadyRead(100));
    QVERIFY(!receiver.hasPendingDatagrams());

    QUdpSocket sender;
    QCOMPARE(sender.writeDatagram(QByteArray(), QHostAddress::LocalHost, receiver.localPort()), qint64(0));

    QVERIFY(receiver.waitForReadyRead(1000));
    QVERIFY(receiver.hasPendingDatagrams());

    char buf;
    QCOMPARE(receiver.readDatagram(&buf, 1), qint64(0));
}
Example #8
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);
}
Example #9
0
// TODO: sendCommand should only take one argument. The second is redundant.
inline static void sendCommand(
        ScreenCommand & command,
        ScreenCommand::WaitMode wait = ScreenCommand::WAIT_BEFORE_UPDATE)
{
    // qDebug("sendCommand at %s", qPrintable(QTime::currentTime().toString("mm:ss.zzz")));
    command.wait_flags = wait;
    socket_.write(reinterpret_cast<const char *>(&command), sizeof(command));
    if (wait & ScreenCommand::WAIT_COMMAND_FINISH)
    {
        if (socket_.waitForReadyRead(3000))
        {
            socket_.read(reinterpret_cast<char *>(&command), sizeof(command));
        }
    }
}
Example #10
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);
    }
}
Example #11
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 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);
    }
}
Example #13
0
void MultiPointCom::run()
{
    mutex.lock();

    QTime timeout = lastConnectTime.addSecs(30);

    if (timeout < QTime::currentTime()) {
        qDebug() << "Device connected timeout" << disconnectCount++;
        lastConnectTime = QTime::currentTime();
#ifdef __arm__
        ioctl(device, SI4432_IOC_RESET, 1);
#endif
    }

#ifdef __arm__
    si4432_ioc_transfer tr;
    char txBuf[64], rxBuf[64];
    memcpy(txBuf, request.data(), request.size());
    memset(&tr, 0, sizeof(si4432_ioc_transfer));
    tr.tx_buf = (__u64)txBuf;
    tr.rx_buf = (__u64)rxBuf;
    tr.len = request.size();
    int len = ioctl(device, SI4432_IOC_MESSAGE(1), &tr);
    if (len > 0) {
        response.clear();
        response.append(rxBuf, len);
        quint8 addr = response.at(0);
        if (addr == address) {
            lastConnectTime = QTime::currentTime();
            disconnect = 0;
            emit deviceConnected();
            emit responseReceived(response.at(1), QByteArray(response.data() + 2, len - 2));
        }
    } else {
        disconnect++;
        if (disconnect > 3) {
            disconnect = 0;
            emit deviceDisconnected();
        }
    }
#else
    QUdpSocket *udp = new QUdpSocket();
    udp->writeDatagram(request, QHostAddress::LocalHost, 19999);

    if (udp->waitForReadyRead(100) && (udp->pendingDatagramSize() > 0)) {
        response.resize(udp->pendingDatagramSize());
        udp->readDatagram(response.data(), response.size());
        quint8 addr = response.at(0);
        if (addr == address) {
            lastConnectTime = QTime::currentTime();
            disconnect = 0;
            emit deviceConnected();
            emit responseReceived(response.at(1), response.mid(2));
        }
    } else {
        disconnect++;
        if (disconnect > 3) {
            disconnect = 0;
            emit deviceDisconnected();
        }
    }
    delete udp;
#endif

    mutex.unlock();
}
Example #14
0
void Udp2MidiThread::run()
{
	QUdpSocket *udpSocket = new QUdpSocket();
	bool bres = udpSocket->bind(PC_PORT);
	if( bres == false ) {
                printf("Could not bind to port %d!\n", PC_PORT);
		return;
	}
	
	forever {
		
		if (abort) {
			delete udpSocket;
			
			return;
		}
		
		if( udpSocket->waitForReadyRead(250) == true ) {
			
			// Receive from UDP
			
			QHostAddress from_address;
                        int len = udpSocket->readDatagram((char*)midimsg, MAX_MIDI_MESSAGE_LENGTH, &from_address);
		
                        if( len == -1 ) {
				printf("udp2midi: Error receiving data!\n");
			}
			
                        if( (len == 3) && (midimsg[0] == 0) && (midimsg[1] == 0) && (midimsg[2] == 0) ) {

				string from_ip = from_address.toString().toStdString();
			
				printf("Keepalive from: %s\n", from_ip.c_str());

				midi2udp->add_ip(from_ip);
			
			} else {

				// Send to MIDI
                                printf("udp2midi: Sending event: ");
                                for(int i=0; i<len; ++i) {
                                    printf("0x%x ", midimsg[i]);
                                }
                                printf("\n");
		
                                long res = snd_midi_event_encode(eventparser, midimsg, len, midi_event);
				
				if( res < 0) {
					printf("Error encoding midi event!\n");
				}
				
				snd_midi_event_reset_encode(eventparser);
				
				if(midi_event->type == SND_SEQ_EVENT_NOTEON) {
					printf("udp2midi: Note on: %d, channel %d\n", midi_event->data.note.note, midi_event->data.control.channel);
				} else if(midi_event->type == SND_SEQ_EVENT_NOTEOFF){
					printf("udp2midi: Note off: %d, channel %d\n", midi_event->data.note.note, midi_event->data.control.channel);
				}
				
				snd_seq_ev_set_subs(midi_event);
				snd_seq_ev_set_direct(midi_event);
				snd_seq_ev_set_source(midi_event, midi_out_port);
				
				snd_seq_event_output_direct(seq_handle, midi_event);
				
				snd_seq_free_event(midi_event);
			}
		}
	}
}
Example #15
0
int main(int argc, char *argv[])
{
    int debugMode = DEBUGMODE;


    if(debugMode)
    {

    } else {
        qInstallMessageHandler(myMessageOutputDisable);

    }

    QDEBUG() << "number of arguments:" << argc;
    QStringList args;
    QDEBUGVAR(RAND_MAX);
    if(argc > 1) {
        QCoreApplication a(argc, argv);
        args = a.arguments();

        QDEBUGVAR(args);

        qRegisterMetaType<Packet>();



        QDEBUG() << "Running command line mode.";

        Packet sendPacket;
        sendPacket.init();
        QString outBuilder;

        QTextStream o(&outBuilder);


        QTextStream out(stdout);

        QDate vDate = QDate::fromString(QString(__DATE__).simplified(), "MMM d yyyy");
        QCoreApplication::setApplicationName("Packet Sender");
        QCoreApplication::setApplicationVersion("version " + vDate.toString("yyyy-MM-dd"));

        QCommandLineParser parser;
        parser.setApplicationDescription("Packet Sender is a Network TCP and UDP Test Utility by Dan Nagle\nSee http://PacketSender.com/ for more information.");
        parser.addHelpOption();
        parser.addVersionOption();

        // A boolean option with a single name (-p)
        QCommandLineOption quietOption(QStringList() << "q" << "quiet", "Quiet mode. Only output received data.");
        parser.addOption(quietOption);


        QCommandLineOption hexOption(QStringList() << "x" << "hex", "Parse data as hex (default).");
        parser.addOption(hexOption);

        QCommandLineOption asciiOption(QStringList() << "a" << "ascii", "Parse data as mixed-ascii (like the GUI).");
        parser.addOption(asciiOption);

        QCommandLineOption pureAsciiOption(QStringList() << "A" << "ASCII", "Parse data as pure ascii (no \\xx translation).");
        parser.addOption(pureAsciiOption);

        // An option with a value
        QCommandLineOption waitOption(QStringList() << "w" << "wait",
                "Wait up to <milliseconds> for a response after sending. Zero means do not wait (Default).",
                "milliseconds");
        parser.addOption(waitOption);

        // An option with a value
        QCommandLineOption fileOption(QStringList() << "f" << "file",
                "Send contents of specified path. Max 1024 for UDP, 10 MiB for TCP.",
                "path");
        parser.addOption(fileOption);


        // An option with a value
        QCommandLineOption bindPortOption(QStringList() << "b" << "bind",
                "Bind port. Default is 0 (dynamic).",
                "port");
        parser.addOption(bindPortOption);


        QCommandLineOption tcpOption(QStringList() << "t" << "tcp", "Send TCP (default).");
        parser.addOption(tcpOption);

        // A boolean option with multiple names (-f, --force)
        QCommandLineOption udpOption(QStringList() << "u" << "udp", "Send UDP.");
        parser.addOption(udpOption);

        // An option with a value
        QCommandLineOption nameOption(QStringList() << "n" << "name",
                                      "Send previously saved packet named <name>. Other options overrides saved packet parameters.",
                                      "name");
        parser.addOption(nameOption);


        parser.addPositionalArgument("address", "Destination address. Optional for saved packet.");
        parser.addPositionalArgument("port", "Destination port. Optional for saved packet.");
        parser.addPositionalArgument("data", "Data to send. Optional for saved packet.");


        // Process the actual command line arguments given by the user
        parser.process(a);

        const QStringList args = parser.positionalArguments();

        bool quiet = parser.isSet(quietOption);
        bool hex = parser.isSet(hexOption);
        bool mixedascii = parser.isSet(asciiOption);
        bool ascii = parser.isSet(pureAsciiOption);
        unsigned int wait = parser.value(waitOption).toUInt();
        unsigned int bind = parser.value(bindPortOption).toUInt();
        bool tcp = parser.isSet(tcpOption);
        bool udp = parser.isSet(udpOption);
        bool ipv6  = false;

        QString name = parser.value(nameOption);

        QString filePath = parser.value(fileOption);


        QString address = "";
        unsigned int port = 0;

        int argssize = args.size();
        QString data, dataString;
        data.clear();
        dataString.clear();
        if(argssize >= 1) {
            address = args[0];
        }
        if(argssize >= 2) {
            port = args[1].toUInt();
        }
        if(argssize >= 3) {
            data = (args[2]);
        }

        //check for invalid options..

        if(argssize > 3) {
            OUTIF() << "Warning: Extra parameters detected. Try surrounding your data with quotes.";
        }

        if(hex && mixedascii) {
            OUTIF() << "Warning: both hex and pure ascii set. Defaulting to hex.";
            mixedascii = false;
        }

        if(hex && ascii) {
            OUTIF() << "Warning: both hex and pure ascii set. Defaulting to hex.";
            ascii = false;
        }

        if(mixedascii && ascii) {
            OUTIF() << "Warning: both mixed ascii and pure ascii set. Defaulting to pure ascii.";
            mixedascii = false;
        }

        if(tcp && udp) {
            OUTIF() << "Warning: both TCP and UDP set. Defaulting to TCP.";
            udp = false;
        }

        if(!filePath.isEmpty() && !QFile::exists(filePath)) {
            OUTIF() << "Error: specified path "<< filePath <<" does not exist.";
            filePath.clear();
            OUTPUT();
            return -1;
        }

        //bind is now default 0

        if(!bind && parser.isSet(bindPortOption)) {
            OUTIF() << "Warning: Binding to port zero is dynamic.";
        }


        if(!port && name.isEmpty()) {
            OUTIF() << "Warning: Sending to port zero.";
        }

        //set default choices
        if(!hex && !ascii && !mixedascii) {
            hex = true;
        }

        if(!tcp && !udp) {
            tcp = true;
        }

        //Create the packet to send.
        if(!name.isEmpty()) {
            sendPacket = Packet::fetchFromDB(name);
            if(sendPacket.name.isEmpty()) {
                OUTIF() << "Error: Saved packet \""<< name <<"\" not found.";
                OUTPUT();
                return -1;
            } else {
                if(data.isEmpty()) {
                    data  = sendPacket.hexString;
                    hex = true;
                    ascii = false;
                    mixedascii = false;
                }
                if(!port) {
                    port  = sendPacket.port;
                }
                if(address.isEmpty()) {
                    address  = sendPacket.toIP;
                }
                if(!parser.isSet(tcpOption) && !parser.isSet(udpOption)) {

                    if(sendPacket.tcpOrUdp.toUpper() == "TCP") {
                        tcp=true;
                        udp = false;
                    } else {
                        tcp=false;
                        udp = true;
                    }

                }

            }

        }

        if(!parser.isSet(bindPortOption)) {
            bind = 0;
        }

        if(!filePath.isEmpty() && QFile::exists(filePath)) {
            QFile dataFile(filePath);
            if(dataFile.open(QFile::ReadOnly)) {

                if(tcp) {
                    QByteArray dataArray = dataFile.read(1024*1024*10);;
                    dataString = Packet::byteArrayToHex(dataArray);
                } else {

                    QByteArray dataArray = dataFile.read(1024);
                    dataString = Packet::byteArrayToHex(dataArray);
                }

                //data format is raw.
                ascii = 0;
                hex = 0;
                mixedascii = 0;

            }
        }



        QDEBUGVAR(argssize);
        QDEBUGVAR(quiet);
        QDEBUGVAR(hex);
        QDEBUGVAR(mixedascii);
        QDEBUGVAR(ascii);
        QDEBUGVAR(address);
        QDEBUGVAR(port);
        QDEBUGVAR(wait);
        QDEBUGVAR(bind);
        QDEBUGVAR(tcp);
        QDEBUGVAR(udp);
        QDEBUGVAR(name);
        QDEBUGVAR(data);
        QDEBUGVAR(filePath);

        //NOW LETS DO THIS!

        if(ascii) { //pure ascii
            dataString = Packet::byteArrayToHex(data.toLatin1());
        }

        if(hex) { //hex
            dataString = Packet::byteArrayToHex(Packet::HEXtoByteArray(data));
        }
        if(mixedascii) { //mixed ascii
            dataString = Packet::ASCIITohex(data);
        }

        if(dataString.isEmpty()) {
            OUTIF() << "Warning: No data to send. Is your formatting correct?";
        }

        QHostAddress addy;
        if(!addy.setAddress(address)) {
            QHostInfo info = QHostInfo::fromName(address);
            if (info.error() != QHostInfo::NoError)
            {
                OUTIF() << "Error: Could not resolve address:" + address;
                OUTPUT();
                return -1;
            } else {
                addy = info.addresses().at(0);
                address = addy.toString();
            }
        }

        QHostAddress theAddress(address);
        if (QAbstractSocket::IPv6Protocol == theAddress.protocol())
        {
           QDEBUG() << "Valid IPv6 address.";
           ipv6 = true;
        }


        QByteArray sendData = sendPacket.HEXtoByteArray(dataString);
        QByteArray recvData;
        recvData.clear();
        int bytesWriten = 0;
        int bytesRead = 0;


        if(tcp) {
            QTcpSocket sock;


            if(ipv6) {
                sock.bind(QHostAddress::AnyIPv6, bind);
            } else {
                sock.bind(QHostAddress::AnyIPv4, bind);
            }
            sock.connectToHost(addy, port);
            sock.waitForConnected(1000);
            if(sock.state() == QAbstractSocket::ConnectedState)
            {
                OUTIF() << "TCP (" <<sock.localPort() <<")://" << address << ":" << port << " " << dataString;
                bytesWriten = sock.write(sendData);
                sock.waitForBytesWritten(1000);
                //OUTIF() << "Sent:" << Packet::byteArrayToHex(sendData);
                if(wait) {
                    sock.waitForReadyRead(wait);
                    recvData = sock.readAll();
                    bytesRead = recvData.size();
                    QString hexString = Packet::byteArrayToHex(recvData);
                    if(quiet) {
                        o << "\n" << hexString;
                    } else {
                        o << "\nResponse Time:" << QDateTime::currentDateTime().toString(DATETIMEFORMAT);
                        o << "\nResponse HEX:" << hexString;
                        o << "\nResponse ASCII:" << Packet::hexToASCII(hexString);
                    }
                }
                sock.disconnectFromHost();
                sock.waitForDisconnected(1000);
                sock.close();

                OUTPUT();
                return bytesWriten;


            } else {
                OUTIF() << "Error: Failed to connect to " << address;

                OUTPUT();
                return -1;
            }


        } else {
            QUdpSocket sock;
            if(ipv6) {
                if(!sock.bind(QHostAddress::AnyIPv6, bind)) {
                    OUTIF() << "Error: Could not bind to " << bind;

                    OUTPUT();
                    return -1;
                }

            } else {
                if(!sock.bind(QHostAddress::AnyIPv4, bind)) {
                    OUTIF() << "Error: Could not bind to " << bind;

                    OUTPUT();
                    return -1;
                }

            }
            OUTIF() << "UDP (" <<sock.localPort() <<")://" << address << ":" << port << " " << dataString;

            bytesWriten = sock.writeDatagram(sendData, addy, port);
            //OUTIF() << "Wrote " << bytesWriten << " bytes";
            sock.waitForBytesWritten(1000);

            if(wait) {
                sock.waitForReadyRead(wait);

                if(sock.hasPendingDatagrams()) {
                    QHostAddress sender;
                    quint16 senderPort;
                    recvData.resize(sock.pendingDatagramSize());

                    sock.readDatagram(recvData.data(), recvData.size(),
                                            &sender, &senderPort);

                    QString hexString = Packet::byteArrayToHex(recvData);
                    if(quiet) {
                        o << "\n" << hexString;
                    } else {
                        o << "\nResponse Time:" << QDateTime::currentDateTime().toString(DATETIMEFORMAT);
                        o << "\nResponse HEX:" << hexString;
                        o << "\nResponse ASCII:" << Packet::hexToASCII(hexString);
                    }
                }
            }

            sock.close();

            OUTPUT();
            return bytesWriten;

        }





        OUTPUT();



    } else {
        QApplication a(argc, argv);

        QDEBUGVAR(args);

        qRegisterMetaType<Packet>();

        QFile file(":/packetsender.css");
        if(file.open(QFile::ReadOnly)) {
           QString StyleSheet = QLatin1String(file.readAll());
         //  qDebug() << "stylesheet: " << StyleSheet;
           a.setStyleSheet(StyleSheet);
        }

        MainWindow w;


        w.show();

        return a.exec();

    }



    return 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();
    }
}
Example #17
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;
}
/**
 * @details
 * Gets the next chunk of data from the UDP socket (if it exists).
 */
void LofarDataSplittingChunker::next(QIODevice* device)
{
    QUdpSocket* socket = static_cast<QUdpSocket*>(device);

    unsigned offsetStream1 = 0;
    unsigned offsetStream2 = 0;
    unsigned prevSeqid = _startTime;
    unsigned prevBlockid = _startBlockid;
    UDPPacket currPacket;
    UDPPacket outputPacket1;
    UDPPacket outputPacket2;
    UDPPacket _emptyPacket1;
    UDPPacket _emptyPacket2;

    WritableData writableData1 = getDataStorage(_nPackets * _packetSizeStream1,
            chunkTypes().at(0));
    WritableData writableData2 = getDataStorage(_nPackets * _packetSizeStream2,
            chunkTypes().at(1));

    unsigned seqid, blockid;
    unsigned totBlocks, lostPackets, diff;
    unsigned packetCounter;

    if (writableData1.isValid() && writableData2.isValid())
    {
        // Loop over the number of UDP packets to put in a chunk.
        for (unsigned i = 0; i < _nPackets; ++i)
        {
            // Chunker sanity check.
            if (!isActive()) return;

            // Wait for datagram to be available.
            while (!socket->hasPendingDatagrams())
                socket->waitForReadyRead(100);

            // Read the current packet from the socket.
            if (socket->readDatagram(reinterpret_cast<char*>(&currPacket), _packetSize) <= 0)
            {
                cerr << "LofarDataSplittingChunker::next(): "
                        "Error while receiving UDP Packet!" << endl;
                i--;
                continue;
            }

            // Check for endianness (Packet data is in little endian format).
#if Q_BYTE_ORDER == Q_BIG_ENDIAN
            // TODO: Convert from little endian to big endian.
            throw QString("LofarDataSplittingChunker: Endianness not supported.");
            seqid   = currPacket.header.timestamp;
            std::cout << seqid << std::endl;
            blockid = currPacket.header.blockSequenceNumber;
#elif Q_BYTE_ORDER == Q_LITTLE_ENDIAN
            seqid   = currPacket.header.timestamp;
            blockid = currPacket.header.blockSequenceNumber;
#endif

            // First time next has been run, initialise startTime and startBlockId.
            if (i == 0 && _startTime == 0) {
                prevSeqid = _startTime = _startTime == 0 ? seqid : _startTime;
                prevBlockid = _startBlockid = _startBlockid == 0 ? blockid : _startBlockid;
            }

            // Sanity check in seqid. If the seconds counter is 0xFFFFFFFF,
            // the data cannot be trusted (ignore).
            if (seqid == ~0U || prevSeqid + 10 < seqid)
            {
                _packetsRejected++;
                i--;
                continue;
            }

            // Check that the packets are contiguous.
            // Block id increments by nrblocks which is defined in the header.
            // Blockid is reset every interval (although it might not start
            // from 0 as the previous frame might contain data from this one).
            totBlocks = (_clock == 160) ?
                    156250 : (prevSeqid % 2 == 0 ? 195313 : 195312);
            lostPackets = 0;
            diff = (blockid >= prevBlockid) ?
                    (blockid - prevBlockid) : (blockid + totBlocks - prevBlockid);

            // Duplicated packets... ignore
            if (diff < _nSamples)
            {
                ++_packetsRejected;
                i -= 1;
                continue;
            }
            // Missing packets
            else if (diff > _nSamples)
            {
                // -1 since it includes this includes the received packet as well
                lostPackets = (diff / _nSamples) - 1;
            }


            if (lostPackets > 0)
            {
                printf("Generate %u empty packets, prevSeq: %u, new Seq: %u, prevBlock: %u, newBlock: %u\n",
                        lostPackets, prevSeqid, seqid, prevBlockid, blockid);
            }

            // TODO
            // BELOW HERE WRITE INTO WRITABLE DATA 1 and 2 correctly.
            //   = Missing packets -> write pair of empty data packets.
            //   = Full packets -> split the packet into the two buffers.
            // =================================================================

            // Generate lostPackets (empty packets) if needed.
            packetCounter = 0;
            for (packetCounter = 0; packetCounter < lostPackets && i + packetCounter < _nPackets; ++packetCounter)
            {
                // Generate empty packet with correct seqid and blockid
                prevSeqid = (prevBlockid + _nSamples < totBlocks) ?
                        prevSeqid : prevSeqid + 1;
                prevBlockid = (prevBlockid + _nSamples) % totBlocks;
                // TODO: probably a cost saving here.
                updateEmptyPacket(_emptyPacket1, prevSeqid, prevBlockid);
                updateEmptyPacket(_emptyPacket2, prevSeqid, prevBlockid);
                offsetStream1 = writePacket(&writableData1, _emptyPacket1, _packetSizeStream1, offsetStream1);
                offsetStream2 = writePacket(&writableData2, _emptyPacket2, _packetSizeStream2, offsetStream2);

                // Check if the number of required packets is reached

                // TODO writePacket(&writableData2, emptyPacket, offset);
            }

            i += packetCounter;

            // Write received packet to 2 streams after updating header and data
            if (i != _nPackets)
            {
                ++_packetsAccepted;

                // Generate Stream 1 packet
                outputPacket1.header = currPacket.header;
                outputPacket1.header.nrBeamlets = _stream1Subbands;
                memcpy((void*)outputPacket1.data, &currPacket.data[_byte1OfStream1], _bytesStream1);
                offsetStream1 = writePacket(&writableData1, outputPacket1, _packetSizeStream1, offsetStream1);

                // Generate Stream 2 packet
                //--------------------------------------------------------------
                outputPacket2.header = currPacket.header;
                outputPacket2.header.nrBeamlets = _stream2Subbands;
                memcpy((void*)outputPacket2.data, &currPacket.data[_byte1OfStream2], _bytesStream2);
                offsetStream2 = writePacket(&writableData2, outputPacket2, _packetSizeStream2, offsetStream2);

                prevSeqid = seqid;
                prevBlockid = blockid;
            }
        }
    }

    else {
        // Must discard the datagram if there is no available space.
        if (!isActive()) return;
        socket->readDatagram(0, 0);
        cout << "LofarDataSplittingChunker::next(): "
                "Writable data not valid, discarding packets." << endl;
    }

    // Update _startTime
    _startTime = prevSeqid;
    _startBlockid = prevBlockid;
}
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();
    }
}
Example #20
0
/**
 * @brief SingleApplication::SingleApplication
 *  Constructor. Checks and fires up LocalServer or closes the program
 *  if another instance already exists
 * @param argc
 * @param argv
 */
SingleApplication::SingleApplication(QStringList &args)
{
  _shouldContinue = false; // By default this is not the main process

  socket = new QUdpSocket();
  QUdpSocket acceptor;
  acceptor.bind(QHostAddress::LocalHost, 58488, QUdpSocket::ReuseAddressHint|QUdpSocket::ShareAddress);

  // Attempt to connect to the LocalServer
  socket->connectToHost(QHostAddress::LocalHost, 58487);
  QString isServerRuns;
  if(socket->waitForConnected(100))
  {
      socket->write(QString("CMD:Is editor running?").toUtf8());
      socket->flush();
      if(acceptor.waitForReadyRead(100))
      {
          //QByteArray dataGram;//Yes, I'm runs!
          QByteArray datagram;
          datagram.resize(acceptor.pendingDatagramSize());
          QHostAddress sender;
          quint16 senderPort;
          acceptor.readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
          if(QString::fromUtf8(datagram)=="Yes, I'm runs!")
          {
              isServerRuns="Yes!";
          }
      }
  }

  if(args.contains("--force-run", Qt::CaseInsensitive))
  {
      isServerRuns.clear();
      args.removeAll("--force-run");
  }
  _arguments = args;

  if(!isServerRuns.isEmpty())
  {
    QString str = QString("CMD:showUp");
    QByteArray bytes;
    for(int i=1; i<_arguments.size(); i++)
    {
       str.append(QString("\n%1").arg(_arguments[i]));
    }
    bytes = str.toUtf8();
    socket->write(bytes);
    socket->flush();
    QThread::msleep(100);
    socket->close();
  }
  else
  {
    // The attempt was insuccessful, so we continue the program
    _shouldContinue = true;
    server = new LocalServer();
    server->start();
    QObject::connect(server, SIGNAL(showUp()), this, SLOT(slotShowUp()));
    QObject::connect(server, SIGNAL(dataReceived(QString)), this, SLOT(slotOpenFile(QString)));
    QObject::connect(server, SIGNAL(acceptedCommand(QString)), this, SLOT(slotAcceptedCommand(QString)));
    QObject::connect(this, SIGNAL(stopServer()), server, SLOT(stopServer()));
  }
}