//----------------------------------------------------------------------------------
void tst_QTcpServer::clientServerLoop()
{
    QTcpServer server;

    QSignalSpy spy(&server, SIGNAL(newConnection()));

    QVERIFY(!server.isListening());
    QVERIFY(!server.hasPendingConnections());
    QVERIFY(server.listen(QHostAddress::Any, 11423));
    QVERIFY(server.isListening());

    QTcpSocket client;

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

    client.connectToHost(serverAddress, server.serverPort());
    QVERIFY(client.waitForConnected(5000));

    QVERIFY(server.waitForNewConnection(5000));
    QVERIFY(server.hasPendingConnections());

    QCOMPARE(spy.count(), 1);

    QTcpSocket *serverSocket = server.nextPendingConnection();
    QVERIFY(serverSocket != 0);

    QVERIFY(serverSocket->write("Greetings, client!\n", 19) == 19);
    serverSocket->flush();

    QVERIFY(client.waitForReadyRead(5000));
    QByteArray arr = client.readAll();
    QCOMPARE(arr.constData(), "Greetings, client!\n");

    QVERIFY(client.write("Well, hello to you!\n", 20) == 20);
    client.flush();

    QVERIFY(serverSocket->waitForReadyRead(5000));
    arr = serverSocket->readAll();
    QCOMPARE(arr.constData(), "Well, hello to you!\n");
}
Exemple #2
0
// Richiesta connessione TCP in ingresso
void DuktoProtocol::newIncomingConnection()
{

    // Verifica presenza connessione pendente
    if (!mTcpServer->hasPendingConnections()) return;

    // Recupero connessione
    QTcpSocket *s = mTcpServer->nextPendingConnection();

    // Se sto già ricevendo o inviando, rifiuto la connessione
    if (mIsReceiving || mIsSending)
    {
        s->close();
        return;
    }

    // Aggiornamento interfaccia grafica
    receiveFileStart();

    // Impostazione socket TCP corrente
    mCurrentSocket = s;

    // Attesa header della connessione (timeout 10 sec)
    if (!s->waitForReadyRead(10000))
    {
        // Non ho ricevuto l'header della connessione, chiudo
        mCurrentSocket->close();
        delete mCurrentSocket;
        mCurrentSocket = NULL;
        return;
    }

    // Registrazione gestori eventi socket
    connect(mCurrentSocket, SIGNAL(readyRead()), this, SLOT(readNewData()), Qt::DirectConnection);
    connect(mCurrentSocket, SIGNAL(disconnected()), this, SLOT(closedConnection()), Qt::QueuedConnection);

    // Inizializzazione variabili
    mIsReceiving = true;
    mTotalReceivedData = 0;
    mElementSize = -1;
    mReceivedFiles = new QStringList();
    mRootFolderName = "";
    mRootFolderRenamed = "";

    // -- Lettura header generale --
    // Numero entità da ricevere
    mCurrentSocket->read((char*) &mElementsToReceiveCount, sizeof(qint64));
    // Dimensione totale
    mCurrentSocket->read((char*) &mTotalSize, sizeof(qint64));

    // Inizio lettura dati sui file
    readNewData();

}
void ConnectionThread::run()
{
    Debug() << "Thread started.";
    QTcpSocket sock;
    socketNoNagle(sockdescr);
    if (!sock.setSocketDescriptor(sockdescr)) {
        Error() << sock.errorString();
        return;
    }
    QString remoteHostPort = sock.peerAddress().toString() + ":" + QString::number(sock.peerPort());
    Log() << "Connection from peer " << remoteHostPort;
    QString line;
    forever {
        if (sock.canReadLine() || sock.waitForReadyRead()) {
            line = sock.readLine().trimmed();
            while (StimApp::instance()->busy()) {
                // special case case, stimapp is busy so keep polling with 1s intervals                
                Debug() << "StimApp busy, cannot process command right now.. trying again in 1 second";
                sleep(1); // keep sleeping 1 second until the stimapp is no longer busy .. this keeps us from getting given commands while we are still initializing
            }
            // normal case case, stimapp not busy,  proceed normally
            QString resp;
            resp = processLine(sock, line);
            if (sock.state() != QAbstractSocket::ConnectedState) {
                Debug() << "processLine() closed connection";
                break;
            }
            if (!resp.isNull()) {
                if (resp.length()) {
                    Debug() << "Sending: " << resp;
                    if (!resp.endsWith("\n")) resp += "\n";
					QByteArray data(resp.toUtf8());
                    int len = sock.write(data);
					if (len != data.length()) {
						Debug() << "Sent "  << len << " bytes but expected to send " << data.length() << " bytes!";
					}
                }
                Debug() << "Sending: OK";
                sock.write("OK\n");
            } else {
                Debug() << "Sending: ERROR";
                sock.write("ERROR\n");
            }            
        } else {
            if (sock.error() != QAbstractSocket::SocketTimeoutError 
                || sock.state() != QAbstractSocket::ConnectedState) {
                Debug() << "Socket error: " << sock.error() << " Socket state: " << sock.state();
                break;
            }
        }
    }
    Log() << "Connection ended (peer: " << remoteHostPort << ")";
    Debug() << "Thread exiting.";
}
Exemple #4
0
void FetchThread::getMunin(t_metric pmetric)
{
    QRegularExpression exp("^munin://([0-9a-zA-Z]+)/([0-9a-zA-Z_]+)/([0-9a-zA-Z.]+)$");  //munin://localhost/load/load.value
    QRegularExpressionMatch match = exp.match(pmetric.source_url);

    if (match.hasMatch() ){
        qDebug() << "FT_getMunin: fetching  " <<  match.captured(1) << "," <<  match.captured(2)  << "," <<  match.captured(3) ;


        QTcpSocket socket;
        socket.connectToHost("localhost", 4949);
        socket.waitForConnected(2000);
        //qDebug() << "FT_getMunin: connected";

        //socket.waitForBytesWritten(1000);

        socket.waitForReadyRead(3000);
        //qDebug() << socket.readAll();
        //qDebug() << "FT_getMunin: request " << match.captured(2);
        socket.write(QString("fetch ").append(match.captured(2)).append(QString("\n")).toStdString().c_str() );

        while (socket.waitForReadyRead(600)){
            QString r = socket.readAll();
            //qDebug() << "FT_getMunin: Server response: " << r;
            QRegularExpression exp2(match.captured(3).append(" ([0-9.]+)\\n"));
            QRegularExpressionMatch match2 = exp2.match(r);
            if (match2.hasMatch() ){
                qDebug() << "FT_getMunin: Got answer : " << match2.captured(1);
                pmetric.qq_item->setProperty("value",this->convert(pmetric, match2.captured(1)));
                pmetric.qq_item->setProperty("text_value",match2.captured(1));

            }
        }

        socket.close();
        //qDebug() << "getMunin: Metric fetch done ";
    } else qDebug() << "getMunin: Illegal metric url: " <<pmetric.source_url;

}
Exemple #5
0
void SFEQuery::Receive(QTcpSocket &socket)
{
    // QDataStream _in((QTcpSocket*)&socket);

    _in.setVersion(QDataStream::Qt_4_7);


    while(socket.bytesAvailable()<sizeof(quint32))
        socket.waitForReadyRead(1000);

    qDebug("reading %d",sizeof(quint32));
    QByteArray ba = socket.read(sizeof(quint32));
    _inblock.append(ba);

    _in >> _size;

    qDebug("cmd size: %d",_size);

   quint32 left = _size- sizeof(quint32);

    while(socket.bytesAvailable()<left){
        qDebug("2 available: %d",(int)socket.bytesAvailable());
        socket.waitForReadyRead(1000);
    }
    qDebug("reading: %d",left);

    QByteArray ba2 = socket.read(left);
    _inblock.append(ba2);
//    _in.skipRawData(sizeof(quint32));
    quint32 type;
    _in >> type;

    qDebug("got type: %d",type);

    if (_type!=SFEQuery::NOTYPE_TYPE && type!=(quint32)_type)
        qDebug("error type !=");
    _type=(SFEQuery::QueryType)type;
    doReceive();
}
Exemple #6
0
void MessageWidget::sendToClient(QString message)
{
    QTcpSocket *socket = new QTcpSocket();
    socket->connectToHost(this->clientIP,4444,QTcpSocket::ReadWrite);
    if (socket->waitForConnected(2000))
    {
        socket->write(message.toLatin1());
        socket->waitForReadyRead(300);
        socket->disconnectFromHost();
    }
    else
        QMessageBox::warning(this,"Connection problem:", "Connection to client failed!", QMessageBox::Close);
    delete socket;
}
bool MainWindow::yearHasData(const int year){
    QUrl url(compBase + "year_" + QString::number(year) + "month_04/day_01/");

    QTcpSocket socket;
    socket.connectToHost(url.host(), 80);
    if (socket.waitForConnected()){
        socket.write("HEAD" + url.path().toUtf8() + "HTTP/1.1\r\n" + "Host" + url.host().toUtf8() + "\r\n\r\n");
        if (socket.waitForReadyRead()){
            QByteArray bytes = socket.readAll();
            if (bytes.contains("200 OK"))
                return true;
        }
    }
    return false;
}
Connection* SharedDaemon::createCustomConnection(int listenSocketNum, void *data)
{
    SharedDaemon::ConnectionType typeOfConnection = *((SharedDaemon::ConnectionType*)(data));
    if(typeOfConnection == SharedDaemon::WSocketConnection )
    {
        int descriptor = SingleThreadedAcceptSocket(listenSocketNum);

        QTcpSocket * tcpSocket = new QTcpSocket();
        tcpSocket->setSocketDescriptor( descriptor, QAbstractSocket::ConnectedState );
        tcpSocket->waitForReadyRead();

        QString request = QString(tcpSocket->readAll());

        if(request.size() == 0) /// firefox works differently, and sends 0 size messages
        {
            tcpSocket->close();
            tcpSocket->disconnectFromHost();
            if(tcpSocket->state() != QAbstractSocket::UnconnectedState)
                tcpSocket->waitForDisconnected();
            tcpSocket->deleteLater();

            descriptor = SingleThreadedAcceptSocket(listenSocketNum);
            tcpSocket = new QTcpSocket();
            tcpSocket->setSocketDescriptor( descriptor, QAbstractSocket::ConnectedState );
            tcpSocket->waitForReadyRead();
            request = QString(tcpSocket->readAll());
        }

        return new WebSocketConnection(tcpSocket,request);
    }
    else
    {
        int descriptor = SingleThreadedAcceptSocket(listenSocketNum);
        return new SocketConnection(descriptor);
    }
}
Exemple #9
0
	void receiveData()
	{
		QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
		clientConnection->waitForReadyRead();
		QDataStream in(clientConnection);
		in.setVersion(QDataStream::Qt_5_4);
		QString text;
		in>>text;
		label->setText(text);
		QString imageFn;
		in>>imageFn;
		if (QFile::exists(imageFn))
		{
			welcome->pictureLabel->setPixmap(QPixmap(imageFn).scaled(welcome->pictureLabel->size(), Qt::KeepAspectRatio));
		}
	}
Exemple #10
0
void cTaskThd::run()
{
	QTcpSocket sck;

	while(1)
	{
		sck.close();
		if(sck.setSocketDescriptor(getsocketDescriptor((cServer *)this->parent())))
			if (sck.waitForReadyRead(SERVICE_TIMEOUT_SEC * 1000))
			{
				qDebug() << "线程" << this->id << " 将数据返回后将关闭连接" ;
				sck.write(sck.readAll());
				sck.waitForBytesWritten(3000);
			}
	}
}
/* FIXME: Qt manuals is saying this is the wrong way to create thread since version 4.x
   we better use QThreadPool or similar but for now...
 */
void SlimIncomingHandler::run()
{
    QString received;
    QTcpSocket tcpSocket;
    if (!tcpSocket.setSocketDescriptor(client))
    {
        qDebug() << "tcpSocket rip?";
        emit error();
        return ;
    }

    bExit = false;
    tcpSocket.write("Slim -- V0.3\r\n");
    while (!bExit) // todo mutex to make possible for server to force exit
    {
        if (tcpSocket.waitForReadyRead(FITNESSE_TIMEOUT))
        {
            received.append(QString(tcpSocket.readAll()));
            qDebug() << received;
            if (received.size() > 6)
            {
                SlimDeserializer dser(received);
                dser.getLength();

                CommandExecuter exe(dser.deserialize());
                QString result = exe.executeAll();
                qDebug() << "resultsend" << result.toUtf8();
                tcpSocket.write(result.toUtf8());
                // fixme failcheck
                received ="";
            }
            // FIXME... parser
            if (received.endsWith("bye")) // the later variant(\r\n) used when debugging since telnet adds \r\n
                break;
        }
        else // timeout waitForDataTimeout
        {
            // tell client to die since there were no data from fitnesse server to process
            qDebug() << "socket timeout";
            bExit = true;
        }
    }
    qDebug() << "die";
    tcpSocket.close();
    emit exited(this);
}
Exemple #12
0
// Richiesta connessione TCP in ingresso
void DuktoProtocol::newIncomingConnection()
{
    // Recieve connection
    QTcpSocket* s = mTcpServer->nextPendingConnection();
    if(s == NULL) return;

    // If we are already recieving or sending
    // Pending header connection (timeout 10 sec)
    if ((mIsReceiving | mIsSending) || !s->waitForReadyRead(10000))
    {
        s->close();
        delete s;
        return;
    }

    // Update GUI
    receiveFileStart(s->peerAddress().toString());

    // set current TCP socket
    mCurrentSocket = s;

    // Register socket's event handlers
    connect(mCurrentSocket, SIGNAL(readyRead()), this, SLOT(readNewData()), Qt::DirectConnection);
    connect(mCurrentSocket, SIGNAL(disconnected()), this, SLOT(closedConnectionTmp()), Qt::QueuedConnection);

    // Initialize variables
    mIsReceiving = true;
    mTotalReceivedData = 0;
    mElementSize = -1;
    mReceivedFiles = new QStringList();
    mRootFolderName.clear();
    mRootFolderRenamed.clear();
    mReceivingText = false;
    mRecvStatus = FILENAME;

    // -- Reading General header --
    // Entities number to receive
    mCurrentSocket->read((char*) &mElementsToReceiveCount, sizeof(qint64));
    // total size
    mCurrentSocket->read((char*) &mTotalSize, sizeof(qint64));

    // Start reading data on file
    readNewData();
}
Exemple #13
0
void ctkSoapConnectionRunnable::run()
{
  QTcpSocket tcpSocket;
  if (!tcpSocket.setSocketDescriptor(socketDescriptor))
  {
    // error handling
    return;
  }


  while (tcpSocket.state() == QTcpSocket::ConnectedState)
  {
    //const int timeout = 5 * 1000;

    tcpSocket.waitForReadyRead(-1);

    readClient(tcpSocket);
  }
}
Exemple #14
0
QByteArray ImapPrivate::readLine (bool *ok) {
    quint8 attempts = 0;
    while (!socket->canReadLine() && attempts < 2) {
        if (!socket->waitForReadyRead())
            attempts++;
    }

    if (attempts >= 2) {
        if (ok != NULL) *ok = false;
        return(QByteArray());
    }

    if (ok != NULL) *ok = true;
#ifdef IMAP_DEBUG
    QByteArray response = socket->readLine();
    qDebug() << "readLine()" << response;
    return(response);
#else
    return(socket->readLine());
#endif
}
Exemple #15
0
QByteArray QQItemInfoHelper::getSingleLongNick(QString id)
{
    QString single_long_nick_url = "/api/get_single_long_nick2?tuin=" + id+ "&vfwebqq=" + CaptchaInfo::instance()->vfwebqq() + "&t=" + QString::number(QDateTime::currentDateTime().toMSecsSinceEpoch());

    Request req;
    req.create(kGet, single_long_nick_url);
    req.addHeaderItem("Host", "s.web2.qq.com");
    req.addHeaderItem("Referer", "http://s.web2.qq.com/proxy.html?v=20110412001&callback=1&id=1");
    req.addHeaderItem("Connection", "keep-live");
    req.addHeaderItem("Content-Type","utf-8");
    req.addHeaderItem("Cookie", CaptchaInfo::instance()->cookie());

    QTcpSocket fd;
    fd.connectToHost("s.web2.qq.com", 80);

    fd.write(req.toByteArray());
    fd.waitForReadyRead();
    QByteArray result = fd.readAll();
    fd.close();

    return result;
}
Exemple #16
0
void CLCServer::readConnection()
{
   QTcpSocket * sock = nextPendingConnection();
   sock->waitForReadyRead();
   QByteArray b = sock->readLine();
   if(b.isEmpty()) return;

   const char * cmd = b.data();

   Arguments * a = parse_commandline(cmd);

   QStringList l;
   l << "CLCBrowser";

   for(int i=1 ; i<a->argc ; ++i)
   {
      l << a->argv[i];
   }
   Arguments_destroy(a);

   parseArgs(l, sock);
   sock->close();
}
Exemple #17
0
void ServerThread::run(){                  // the main thread loop
    QTcpSocket clientSocket;               // the clientSocket object
    this->running = true;                  // the main thread loop bool flag
    if (!clientSocket.setSocketDescriptor(socketDescriptor)){ //set up socket
        qDebug() << "Failed to setup the Socket";  // debug output
    }
    while(running){                        // loop forever until flag changes
       if(!clientSocket.waitForReadyRead(1000)){ // wait for up to 1 sec.
           this->running = false;                // failed - exit the loop
       }
       while(clientSocket.bytesAvailable()>0)    // are bytes available?
       {
           int x = clientSocket.bytesAvailable();  // how many?
           qDebug() << "There are " << x << " bytes available"; //debug
           char data[2000];                // capacity for up to 2000 bytes
           x = (qint64) clientSocket.read(&data[0], (qint64) x);
           data[x] = '\0';                 // add null in case of print output
           this->parse(&data[0]);          // parse the XML string
       }
    }
    clientSocket.close();                  // if loop finished, close socket
    qDebug() << "The client just disconnected";    // debug output
}
Exemple #18
0
TEST_F(SocketTest, socketSendsOutgoingDataUsingQDataStream_Test)
{
    QTcpServer server;
    server.listen(HOST, PORT);
    _socket->connectToHost(HOST, PORT);
    bool timedOut = false;
    EXPECT_TRUE(server.waitForNewConnection(TCP_TIMEOUT_MS, &timedOut));
    EXPECT_FALSE(timedOut);
    QTcpSocket* serverSocket = server.nextPendingConnection();
    EXPECT_THAT(serverSocket, NotNull());
    flushEvents();
    EXPECT_EQ(QAbstractSocket::ConnectedState, _socket->state());
    EXPECT_EQ(QAbstractSocket::ConnectedState, serverSocket->state());

    QDataStream out(_socket->ioDevice());
    out << static_cast<quint32>(42);
    EXPECT_TRUE(_socket->ioDevice()->waitForBytesWritten(TCP_TIMEOUT_MS));
    EXPECT_TRUE(serverSocket->waitForReadyRead(TCP_TIMEOUT_MS));

    quint32 i = 0;
    QDataStream in(serverSocket);
    in >> i;
    EXPECT_EQ(static_cast<quint32>(42), i);
}
Exemple #19
0
int main(int argv, char **args)
{
    QCoreApplication app(argv, args);

    QTcpSocket socket;
    socket.connectToHost("localhost", 1025);
    
//! [0]
    int numRead = 0, numReadTotal = 0;
    char buffer[50];

    forever {
	numRead  = socket.read(buffer, 50);

	// do whatever with array
	
	numReadTotal += numRead;
	if (numRead == 0 && !socket.waitForReadyRead()) 
	    break;
    }
//! [0]
    
    return app.exec();
}
void getActiveCellProperty(Matrix& propertyFrames, const QString &serverName, quint16 serverPort,
                        const qint64& caseId, QString propertyName, const int32NDArray& requestedTimeSteps, QString porosityModel)
{
    QTcpSocket socket;
    socket.connectToHost(serverName, serverPort);

    if (!socket.waitForConnected(riOctavePlugin::connectTimeOutMilliSecs))
    {
        error((("Connection: ") + socket.errorString()).toLatin1().data());
        return;
    }

    QDataStream socketStream(&socket);
    socketStream.setVersion(riOctavePlugin::qtDataStreamVersion);

    // Create command as a string with arguments , and send it:

    QString command;
    command += "GetActiveCellProperty " + QString::number(caseId) + " " + propertyName + " " + porosityModel;

    for (int i = 0; i < requestedTimeSteps.length(); ++i)
    {
        if (i == 0) command += " ";
        command += QString::number(static_cast<int>(requestedTimeSteps.elem(i)) - 1); // To make the index 0-based
        if (i != requestedTimeSteps.length() -1) command += " ";
    }

    QByteArray cmdBytes = command.toLatin1();

    socketStream << (qint64)(cmdBytes.size());
    socket.write(cmdBytes);

    // Get response. First wait for the header

    while (socket.bytesAvailable() < (int)(2*sizeof(quint64)))
    {
        if (!socket.waitForReadyRead(riOctavePlugin::longTimeOutMilliSecs))
        {
            error((("Waiting for header: ") + socket.errorString()).toLatin1().data());
            return;
        }
    }

    // Read timestep count and blocksize

    quint64 timestepCount;
    quint64 byteCount;
    size_t  activeCellCount;

    socketStream >> timestepCount;
    socketStream >> byteCount;

    activeCellCount = byteCount / sizeof(double);
    propertyFrames.resize(activeCellCount, timestepCount);

    if (!(byteCount && timestepCount))
    {
        error ("Could not find the requested data in ResInsight");
        return;
    }

    // Wait for available data for each timestep, then read data for each timestep

    for (size_t tIdx = 0; tIdx < timestepCount; ++tIdx)
    {
        while (socket.bytesAvailable() < (int)byteCount)
        {
            if (!socket.waitForReadyRead(riOctavePlugin::longTimeOutMilliSecs))
            {
                error((("Waiting for timestep data number: ") + QString::number(tIdx)+  ": " + socket.errorString()).toLatin1().data());
                octave_stdout << "Active cells: " << activeCellCount << ", Timesteps: " << timestepCount << std::endl;
                return ;
            }
           OCTAVE_QUIT;
        }

        qint64 bytesRead = 0;
        double * internalMatrixData = propertyFrames.fortran_vec();

#if 0
        // Raw data transfer. Faster. Not possible when dealing with coarsening
        // bytesRead = socket.read((char*)(internalMatrixData + tIdx * activeCellCount), byteCount);
#else
        // Compatible transfer. Now the only one working
        for (size_t cIdx = 0; cIdx < activeCellCount; ++cIdx)
        {
            socketStream >> internalMatrixData[tIdx * activeCellCount + cIdx];

            if (socketStream.status() == QDataStream::Ok) bytesRead += sizeof(double);
        }
#endif

        if ((int)byteCount != bytesRead)
        {
            error("Could not read binary double data properly from socket");
            octave_stdout << "Active cells: " << activeCellCount << ", Timesteps: " << timestepCount << std::endl;
        }

        OCTAVE_QUIT;
    }

    QString tmp = QString("riGetActiveCellProperty : Read %1").arg(propertyName);

    if (caseId < 0)
    {
        tmp += QString(" from current case.");
    }
    else
    {
        tmp += QString(" from case with Id: %1.").arg(caseId);
    }
    octave_stdout << tmp.toStdString() << " Active cells : " << activeCellCount << ", Timesteps : " << timestepCount << std::endl;

    return;
}
Exemple #21
0
void MySocketClient::run()
{
    cout << "Starting MySocketClient::run()" << endl;
    QTcpSocket tcpSocket;

    // ON RECUPERE LE LIEN DE COMMUNICATION AVEC LE CLIENT ET ON QUITTE EN CAS
    // DE PROBLEME...
    if (!tcpSocket.setSocketDescriptor(socketDescriptor)) {
        emit error(tcpSocket.error());
        return;
    }

    // SI LE CLIENT N'A PAS EU LE TEMPS DE NOUS TRANSMETTRE SA REQUETE,
    // ON SE MET EN ATTENTE PENDANT 1s
    while (tcpSocket.bytesAvailable() < (int)sizeof(quint16)) {
        if (!tcpSocket.waitForReadyRead( 1000 )) {
                cout << "(EE) Erreur de time out !" << endl;
                return;
        }
    }

    // LA PREMIERE REQUETE CORRESPOND AU GET NORMALEMENT
    char tampon[65536];

    // ON RECUPERE LA REQUETE ET SA TAILLE
    int lineLength = tcpSocket.readLine(tampon, 65536);

    // ON TRANSFORME LA REQUETE SOUS FORME DE STRING
    string ligne( tampon );
    ligne = removeEndLine( ligne );

    // ON AFFICHE LA COMMANDE A L'ECRAN...
    cout << "COMMANDE : =>" << ligne << "<=" << endl;

   int pos1 = ligne.find(" ");
   string cmde = ligne.substr(0, pos1);
   ligne = ligne.substr(pos1+1, ligne.length()-pos1);

   cout << "1. : " << cmde  << endl;
   cout << "2. : " << ligne << endl;

   int pos2 = ligne.find(" ");
   string file = ligne.substr(0, pos2);
   ligne = ligne.substr(pos2+1, ligne.length()-pos2);

   cout << "3. : " << file  << endl;
   cout << "4. : '" << ligne << "'" << endl;

        while( tcpSocket.bytesAvailable() > 0 ){
        lineLength = tcpSocket.readLine(tampon, 65536);
        if (lineLength != -1 &&  lineLength != 0) {
                //cout << "C" << lineLength << " :: " << tampon;
        }else if(lineLength != -1 ){
                cout << "Nothing for the moment !" << endl;
        }
    }

    QString str = tr("./public_html") + tr(file.c_str()); //Adresse du fichier ou dossier (./public_html//essai.html)
    statistiques->AddPeer(tcpSocket.peerAddress().toString());
    statistiques->AddRequete(str);
    QByteArray temp("");
    QFile f( str );
    QDir  d( str );
    bool found;

    if( f.exists() == true )
    {
        statistiques->AddFile(f.fileName());
    }


    found = str.contains("statistiques.html", Qt::CaseInsensitive) ||str.contains("???", Qt::CaseInsensitive) ;
    if(found==true)
    {
       temp = statistiques->GenerateHtml();

    }

    else
    {
        if(!MyHash->contains( str ))    /* si le hash ne contient pas ce fichier*/
        {                               /*alors on ajoute la page dans Hash*/

            cout << " - Chemin du fichier : " << str.toStdString() << endl;
            cout << " - isFile :          : " << f.exists() << endl;
            cout << " - isDirectory       : " << d.exists() << endl;

            if( f.exists() == false &&  d.exists() == false )
            {
                str = tr("erreur404");
            }
            else if( d.exists() == true )//LE CHAMP SAISI EST UN REPERTOIRE
            {
                QByteArray* NewByteArray = new QByteArray;

                *NewByteArray = "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Type: text/html\r\n\n";
                for(int i = 0 ; i < d.entryList().size() ; i++)
                {
                    *NewByteArray+=QByteArray("<p>") + QByteArray("<a href=\"")+QString::fromStdString(file);
                    if(QString::compare(QString::fromStdString(file),QString("/")))//Dans le cas d'un sous dossier il faut rajouter un / dans le path
                        *NewByteArray+=QByteArray("/");
                    *NewByteArray+=d.entryList()[i]+QByteArray("\">")+d.entryList()[i] +QByteArray("</a></p>");
                }
                MyHash->insert(str, NewByteArray);
                *MyHashSize+=NewByteArray->size();
                MyHashKeys->append(str);
            }
            else if( f.exists() == true )/* On ajoute le fichier dans le Hash en ByteArray*/
            {

                QFile* file = new QFile( str );

                 if (!file->open(QIODevice::ReadOnly))
                 {
                         delete file;
                         return;
                 }

                 /*concatener des types QByteArray? avec le +
                 utiliser l'en tête ci-dessous
                 HTTP/1.1 200 OK
                 Connection: close
                 Content-Type: text/html
                 construction de cette en-tête HTTP, il est nécessaire de la faire suivre par un saut de ligne
                 avant la partie html*/

                 QByteArray* NewByteArray = new QByteArray;

                 found = str.contains(".jpg", Qt::CaseInsensitive);
                 if (found==true)
                 {
                     *NewByteArray = "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Type: image/jpeg\r\n\n";
                     // creation d'un QbyteArray indiquant une image au format jpeg
                 }

                 found = str.contains(".html", Qt::CaseInsensitive);
                 if (found==true)
                 {
                     *NewByteArray = "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Type: text/html\r\n\n";
                     // creation d'un QbyteArray indiquant un texte au format html
                 }

                 found = str.contains(".pdf", Qt::CaseInsensitive);
                 if (found==true)
                 {
                     *NewByteArray = "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Type: application/pdf\r\n\n";
                     // creation d'un QbyteArray indiquant un texte au format html
                 }

                 found = str.contains(".mp3", Qt::CaseInsensitive);
                 if (found==true)
                 {
                     *NewByteArray = "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Type: audio/mp3\r\n\n";
                     // creation d'un QbyteArray indiquant un texte au format html
                 }
                 found = str.contains(".doc", Qt::CaseInsensitive) || str.contains(".docx", Qt::CaseInsensitive);
                 if (found==true)
                 {
                     *NewByteArray = "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document\r\n\n";
                 }
                 found = str.contains(".pptx", Qt::CaseInsensitive);
                 if (found==true)
                 {
                     *NewByteArray = "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Type: application/vnd.ms-powerpoint\r\n\n";
                 }


                 *NewByteArray += file->readAll();


                 // temp a été redimensionné automatiquement

                 file->close();
                 MyHash->insert(str, NewByteArray);/*insère bytearray dans Hash*/
                 *MyHashSize+=NewByteArray->size();
                 MyHashKeys->append(str);
            }
            else
            {
                 str =tr("erreur404");
            }


        }
        else //requete deja dans le hash        
            MyHashKeys->append(MyHashKeys->takeAt(MyHashKeys->lastIndexOf(str))); //on met la key en derniere position de la liste (premiere pos = LRU)

        temp = *MyHash->value(str);

    }
    if(str.contains("erreur404"))
        statistiques->AddErreur404();
    else
        statistiques->AddTraitee();
    statistiques->AddOctets(temp.size());
    tcpSocket.write(temp);


    //Gestion de la taille du cache, suppression du LRU (last recently used)
    while(*MyHashSize > CACHE_SIZE && MyHash->count()>1 )//Tant qu'on ne dépasse pas la taille max et qu'il reste plus d'un item dans le Hash (on ne veut pas supprimer erreur 404)
    {
        *MyHashSize-=MyHash->value(MyHashKeys->first())->size();//On soustrait la taille du fichier qu'on va enlever
        delete MyHash->value(MyHashKeys->first());
        MyHash->remove(MyHashKeys->first());//On retire le LRU du cache
        MyHashKeys->removeFirst();//on enlève la LRU key

    }

//    for(int i = 0;i<MyHashKeys->size();i++)
//        cout<<MyHashKeys->value(i).toStdString()<<endl;
//    cout<<*MyHashSize<<endl;

    statistiques->SetCacheSize(*MyHashSize);
    cout << "Finishing MySocketClient::run()" << endl;

//! [2] //! [3]
    tcpSocket.disconnectFromHost();
    tcpSocket.waitForDisconnected();


}
int tcp_ping(QStringList command) {
    qDebug() << "tcp_ping(" << command.join(" ") << ")" << endl;

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

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

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

    QByteArray byteArray;

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

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

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

        // Header: request (1), profile (1), version (1), channel (1)
        byteArray.append(QByteArray(4, '\0'));

        // Header: UUID (16)
        QUuid uuid;
        uuid = QUuid::createUuid();
        QByteArray uuid_arr = uuid.toRfc4122();

        for(int j=0; j<16;j++) {

            byteArray.append(uuid_arr.at(j));
        }

        // Header: Empty IP address (4), port number (2), time (8), type (1), size (1)
        byteArray.append(QByteArray(16, '\0'));

        // Contextinformation: type (1), root-CIC (2), size (1)
        byteArray.append(QByteArray(4, '\0'));

        // Application: type (1), size (1)
        byteArray.append(QByteArray(2, '\0'));
     }

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

        // Header: fix
        byteArray.append(QByteArray(34, '\0'));

        // Header: size (1)
        byteArray.append(QByteArray(QByteArray::fromHex("0xff")));
        byteArray.append(QByteArray(255, '\0'));

        // Contextinformation: fix
        byteArray.append(QByteArray(2, '\0'));

        // Contextinformation: size (255)
        byteArray.append(QByteArray(QByteArray::fromHex("0xff")));
        byteArray.append(QByteArray(255*2, '\0'));

        // Application Data: fix
        byteArray.append(QByteArray(0, '\0'));

        // Application Data: size (255)
        byteArray.append(QByteArray(QByteArray::fromHex("0xff")));
        byteArray.append(QByteArray(255, '\0'));


     }

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

        QByteArray randValues;
        qsrand(QTime::currentTime().msec());
        for(int i=0; i <= 1064; i++) {
            randValues.append(qFloor(qrand()/CRN_RANDOM_DIVISOR));
        }


        int i = 0;
        quint8 rand;

        // Header: request (1)
        byteArray.append(randValues.at(i++));


        // Header: profile (1)
        byteArray.append(randValues.at(i++));


        // Header: version (1)
        byteArray.append(randValues.at(i++));


        // Header: channel (1)
        byteArray.append(randValues.at(i++));

        // Header: UUID (16)
        QUuid uuid;
        uuid = QUuid::createUuid();
        QByteArray uuid_arr = uuid.toRfc4122();

        for(int j=0; j<16;j++) {

            byteArray.append(uuid_arr.at(j));
        }

        // Header: Empty IP address (4) and port number (2)
        byteArray.append(QByteArray(6, '\0'));

        // Header: time (8)
        byteArray.append(QByteArray(8, '\0'));

        // Header: type (1)
        byteArray.append(randValues.at(i++));

        // Header: size (1) and data
        rand = randValues.at(i++);
        byteArray.append(rand);
        byteArray.append(QByteArray(rand, rand));

        // Contextinformation: type (1)
        byteArray.append(randValues.at(i++));

        // Contextinformation: root-CIC (2)
        byteArray.append(randValues.at(i++));
        byteArray.append(randValues.at(i++));

        // Contextinformation: size (1)
        rand = randValues.at(i++);
        byteArray.append(rand);
        byteArray.append(QByteArray(rand*2, rand));

        // Application: type (1)
        byteArray.append(randValues.at(i++));

        // Application: size (1)
        rand = randValues.at(i++);
        byteArray.append(rand);
        byteArray.append(QByteArray(rand, rand));

    } // rand

    /**
     * Sent via TCP
     */
    QTcpSocket *tcpSocket;
    tcpSocket = new QTcpSocket();
    QTextStream outStream(stdout);

    QString out;

    tcpSocket->abort();
    tcpSocket->connectToHost("127.0.0.1", 22365);

    qDebug() << "waitForConnected!";
    if (tcpSocket->waitForConnected(5000)) {

        qDebug() << "Connected!";
    }
    else {
        errorStream << "Error: tcp_ping(" << command.join(" ") << ") No connection available!" << endl;
        return 1;
    }

    out = QString("BytesWritten: %1").arg(tcpSocket->write(byteArray, byteArray.length()));

    qDebug() << out;

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

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

        qDebug() << buffer;

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

    tcpSocket->flush();
    tcpSocket->disconnectFromHost();
    tcpSocket->close();

    outStream << out << endl;

    return 0;
}
void getPropertyNames(std::vector<QString>& propNames, std::vector<QString>& propTypes, const QString &hostName, quint16 port, 
                        const qint64& caseId, QString porosityModel)
{
    QString serverName = hostName;
    quint16 serverPort = port;

    QTcpSocket socket;
    socket.connectToHost(serverName, serverPort);

    if (!socket.waitForConnected(riOctavePlugin::connectTimeOutMilliSecs))
    {
        error((("Connection: ") + socket.errorString()).toLatin1().data());
        return;
    }

    // Create command and send it:

    QString command;
    command += QString("GetPropertyNames") + " " + QString::number(caseId) + " " + porosityModel;
    QByteArray cmdBytes = command.toLatin1();

    QDataStream socketStream(&socket);
    socketStream.setVersion(riOctavePlugin::qtDataStreamVersion);

    socketStream << (qint64)(cmdBytes.size());
    socket.write(cmdBytes);

    // Get response. First wait for the header

    while (socket.bytesAvailable() < (int)(sizeof(quint64)))
    {
        if (!socket.waitForReadyRead(riOctavePlugin::shortTimeOutMilliSecs))
        {
            error((("Waiting for header: ") + socket.errorString()).toLatin1().data());
            return;
        }
    }

    quint64 byteCount;
    socketStream >> byteCount;
    QString byteCountString = QString::number(byteCount);

    //error(byteCountString.toLatin1().data());

    while (socket.bytesAvailable() < (int)(byteCount))
    {
        if (!socket.waitForReadyRead(riOctavePlugin::shortTimeOutMilliSecs))
        {
            error((("Waiting for data: ") + socket.errorString()).toLatin1().data());
            return;
        }
        OCTAVE_QUIT;
    }

    quint64 propCount;
    socketStream >> propCount;

    QString propName;
    QString propType;

    for (size_t i = 0; i < propCount; i++)
    {
        socketStream >> propName;
        socketStream >> propType;

        propNames.push_back(propName);
        propTypes.push_back(propType);
    }

    return;
}
Exemple #24
0
void MessageWidget::newConnection()
{
    QTcpSocket *socket = this->tcpServer.nextPendingConnection();
    if (socket->waitForReadyRead(2000))
    {
        QString output= QString::fromUtf8(socket->readAll());


        if (output.contains(QRegExp("^SMS_RECEIVED:")))
        {//"SMS_RECEIVED:number:body
            output.remove(QRegExp("^SMS_RECEIVED:"));

            int i;
            QString number,body;

            i = output.indexOf(":");
            number = output.left(i);
            output.remove(0,i+1);

            i = output.indexOf(":");
            body = output;

            emit this->smsReceived(this->contactModel.getName(number),body);
        }
        else if (output.contains(QRegExp("^GET_SMS_LIST:")))
        {//"GET_SMS_LIST:threadId:messageId:timestamp:number:read:toa:body
            output.remove(QRegExp("^GET_SMS_LIST:"));
            int i;
            QString threadId,messageId,timestamp,number,read,toa,body;

            i = output.indexOf(":");
            threadId = output.left(i);
            output.remove(0,i+1);

            i = output.indexOf(":");
            messageId = output.left(i);
            output.remove(0,i+1);

            i = output.indexOf(":");
            timestamp = output.left(i);
            output.remove(0,i+1);

            i = output.indexOf(":");
            number = output.left(i);
            output.remove(0,i+1);

            i = output.indexOf(":");
            read = output.left(i);
            output.remove(0,i+1);

            i = output.indexOf(":");
            toa = output.left(i);
            output.remove(0,i+1);

            i = output.indexOf(":");
            body = output;

            addSMS(threadId,messageId,timestamp,number,read,toa,body);
        }
        else if (output.contains(QRegExp("^GET_CONTACT_LIST:")))
        {
            output.remove(QRegExp("^GET_CONTACT_LIST:"));
            QString id,number,name;
            int i;

            i = output.indexOf(":");
            id = output.left(i);
            output.remove(0,i+1);

            i = output.indexOf(":");
            name = output.left(i);
            output.remove(0,i+1);

            i = output.indexOf(":");
            number = output;
            number.remove("\n");

            addContact(id,number,name);
        }

        socket->disconnectFromHost();
    }
    delete socket;
}
Exemple #25
0
void getDynamicNNCValues(Matrix& propertyFrames, const QString &serverName, quint16 serverPort,
                         const qint64& caseId, QString propertyName, const int32NDArray& requestedTimeSteps)
{
    QTcpSocket socket;
    socket.connectToHost(serverName, serverPort);

    if (!socket.waitForConnected(riOctavePlugin::connectTimeOutMilliSecs))
    {
        error((("Connection: ") + socket.errorString()).toLatin1().data());
        return;
    }

    QDataStream socketStream(&socket);
    socketStream.setVersion(riOctavePlugin::qtDataStreamVersion);

    // Create command as a string with arguments , and send it:
    QString command;
    command += "GetDynamicNNCValues " + QString::number(caseId) + " " + propertyName;

    for (int i = 0; i < requestedTimeSteps.length(); ++i)
    {
        if (i == 0) command += " ";
        command += QString::number(static_cast<int>(requestedTimeSteps.elem(i)) - 1); // To make the index 0-based
        if (i != requestedTimeSteps.length() -1) command += " ";
    }

    QByteArray cmdBytes = command.toLatin1();

    socketStream << (qint64)(cmdBytes.size());
    socket.write(cmdBytes);

    // Get response. First wait for the header

    while (socket.bytesAvailable() < (int)(2*sizeof(quint64)))
    {
        if (!socket.waitForReadyRead(riOctavePlugin::longTimeOutMilliSecs))
        {
            error((("Waiting for header: ") + socket.errorString()).toLatin1().data());
            return;
        }
    }

    // Read connection count and timestep count
    quint64 connectionCount;
    quint64 timestepCount;

    socketStream >> connectionCount;
    socketStream >> timestepCount;

    propertyFrames.resize(connectionCount, timestepCount);

    if (!(connectionCount && timestepCount))
    {
        error ("Could not find the requested data in ResInsight");
        return;
    }

    quint64 totalByteCount = timestepCount * connectionCount * sizeof(double);

    double* internalMatrixData = propertyFrames.fortran_vec();
    QStringList errorMessages;
    if (!RiaSocketDataTransfer::readBlockDataFromSocket(&socket, (char*)(internalMatrixData), totalByteCount, errorMessages))
    {
        for (int i = 0; i < errorMessages.size(); i++)
        {
            error(errorMessages[i].toLatin1().data());
        }

        return;
    }

    QString tmp = QString("riGetDynamicNNCValues : Read %1").arg(propertyName);

    if (caseId < 0)
    {
        tmp += QString(" from current case.");
    }
    else
    {
        tmp += QString(" from case with Id: %1.").arg(caseId);
    }
    octave_stdout << tmp.toStdString() << " Connections: " << connectionCount << ", Time steps : " << timestepCount << std::endl;

    return;
}
Exemple #26
0
void QMplayer::newConnection()
{
    QTcpSocket *con = tcpServer->nextPendingConnection();
    connect(con, SIGNAL(disconnected()),
            con, SLOT(deleteLater()));

    QByteArray req;
    while(con->waitForReadyRead(100))
    {
        req += con->readAll();
    }

    QString res;
    QTextStream buf(&req);
    buf.setCodec(QTextCodec::codecForName("utf8"));
    QString line;
    QString reqPath = "";           // path from http request
    QString filename = "";          // file on the disk
    QString encPath = "";           // transcoded file
    QString host = "";
    QFile file;
    bool sendFile = false;
    int itemIndex = 0;

    for(;;)
    {
        line = buf.readLine();
        if(line.isNull())
        {
            break;
        }
        if(line.startsWith("GET "))
        {
            int index = req.indexOf(' ', 4);
            if(index > 0)
            {
                reqPath = req.mid(4, index - 4);
                for(int i = 0; i < reqPath.count(); i++)
                {
                    if(reqPath.at(i) == '%')
                    {
                        i += 2;
                        if(i >= reqPath.count())
                        {
                            break;
                        }
                        QChar ch = (QChar)(reqPath.mid(i - 1, 2).toInt(0, 16));
                        reqPath.replace(i - 2, 3, ch);
                    }
                }
            }
        }
        else if(line.startsWith("Host: "))
        {
            host = line.right(line.length() - 6).trimmed();
        }
    }

    res.append("HTTP/1.0 200 OK\r\n");
    res.append("Content-Type: text/html; charset=utf-8\r\n\r\n");
    res.append("<html>");
    res.append("<body>");

    if(reqPath.length() == 0)
    {
        res.append("Valid GET request not found");
    }
    else if(host.length() == 0)
    {
        res.append("Host not found in html header");
    }
    else if(reqPath == "/")
    {
        QString dir = "";
        for(int i = NUM_MENU_ITEMS; i < lw->count(); i++)
        {
            QListWidgetItem *item = lw->item(i);
            QString path = item->text();
            bool isDir = isDirectory(path);
            if(isDir)
            {
                res.append(path);
                res.append("</br>");
                dir = pathToUrl(path);
            }
            else
            {
                res.append("\r\n<a href=\"http://");
                res.append(host);
                res.append(dir);
                res.append(pathToUrl(path));
                res.append("\">");
                res.append(path);
                res.append("</a></br>\r\n");
            }
        }
    }
    else
    {
        res.append(reqPath);
        res.append("</br>");
        QString dir = "";
        QString testDir;
        for(int i = NUM_MENU_ITEMS; i < lw->count(); i++)
        {
            QListWidgetItem *item = lw->item(i);
            QString path = item->text();
            QString testPath = pathToUrl(path);
            bool isDir = isDirectory(path);
            if(isDir)
            {
                dir = path;
                testDir = testPath;
            }
            else if(reqPath == (testDir + testPath))
            {
                filename = dir;
                if(!filename.endsWith('/') && !filename.endsWith('\\'))
                {
                    filename.append('/');
                }
                filename.append(path);
                itemIndex = i;
                break;
            }
        }
        if(filename.length() == 0)
        {
            res.append("file not found");
        }
        else
        {
            encPath = getEncFilename(filename, ".qmplayer");
            QFileInfo fi(encPath);
            if(fi.exists())
            {
                QString size;
                size.setNum(fi.size());
                res.append("file size: ");
                res.append(size);

                if(processRunning(process))
                {
                    res.append("</br>encoding in progress</br>Reload page to check status or download");
                }
                else
                {
                    QString mime = "text/plain";
                    if(reqPath.endsWith(".avi"))
                    {
                        mime ="video/avi";
                    }
                    else if(reqPath.endsWith(".mp4"))
                    {
                        mime = "video/mp4";
                    }
                    else if(reqPath.endsWith(".ogv"))
                    {
                        mime = "video/theora";
                    }
                    else if(reqPath.endsWith(".ogg"))
                    {
                        mime = "audio/vorbis";
                    }
                    else if(reqPath.endsWith(".mp3"))
                    {
                        mime = "audio/mpeg";
                    }
                    else if(reqPath.endsWith(".flac"))
                    {
                        mime = "audio/flac";
                    }

                    res.clear();
                    res.append("HTTP/1.0 200 OK\r\n");
                    res.append("Content-Type: ");
                    res.append(mime);
                    res.append("\r\nContent-Length: ");
                    res.append(size);
                    res.append("\r\n\r\n");

                    sendFile = true;
                }
            }
            else if(processRunning(process))
            {
                res.append("Another encoding is in progress");
            }
            else
            {
                if(startMencoder(filename, encPath))
                {
                    // FIXME: whatever we send to back, browser wont show anything
                    res.append("Encoding started</br>Reload page to check status or download");
                }
                else
                {
                    res.append("Failed to start mencoder:</br>");
                    res.append(process->errorString());
                }
            }
        }
    }

    if(!sendFile)
    {
        res.append("</body>");
        res.append("</html>");
    }
    con->write(res.toUtf8());

    if(sendFile)
    {
        QFile f(encPath);
        char buf[4096];
        f.open(QFile::ReadOnly);
        int count;
        while((count = f.read(buf, 4096)) > 0)
        {
            con->write(buf, count);
            con->flush();
            con->waitForBytesWritten(-1);
        }
    }

    con->close();
    con->disconnectFromHost();
}
Exemple #27
0
void Task::run() {
    QTcpSocket socket;
    QString answerID,type,lang;
    socket.setSocketDescriptor(this->socketDescriptor);
    socket.waitForReadyRead();
    data=socket.readAll();
    dateTime = QDateTime::currentDateTime();
    QStringList params;
    QFile file;
    token=QUuid::createUuid().toString();
    token=token.left(token.size()-1);
    token=token.right(token.size()-1);
    conName=cdb.connectionName()+QString::number(id);
    {
        QSqlDatabase db=QSqlDatabase(QSqlDatabase::cloneDatabase(cdb,conName));
        db.open();
        QSqlQuery query(db);

        sc = engine.evaluate("(" + QString(data) + ")");
        QScriptValueIterator it(sc);
        while (it.hasNext()) {
            it.next();
            if (it.name()=="program")
            {
                program_id=it.value().toString();
                token=token+"-"+program_id;
                params<<program_id;
                if (!params.at(0).isNull()||!params.at(0).isEmpty())
                {
                    query.exec("INSERT INTO math.answer (an_user_id, an_token, an_complete,  an_start_date, an_cp_id) VALUES (0, '"+token+"', 0,  '"+dateTime.toString("yyyy-MM-dd hh:mm:ss")+"', '"+program_id+"');");
                    query.exec("SELECT @an_id:=LAST_INSERT_ID();");
                    query.next();
                    answerID = query.value(0).toString();
                    params<<answerID;
                }
            }
            if (it.name()=="exec")
            {
                type=it.value().toString();
            }
            if (it.name()=="lang")
            {
                lang=it.value().toString();
                params<<lang;
            }
            if (it.value().isObject())
            {
                if (type=="execute")
                {
                    QScriptValueIterator sit(it.value());
                    while (sit.hasNext()) {
                        sit.next();
                        if (sit.value().isObject())//--- jeigu tai failas
                        {
                            QScriptValueIterator sits(sit.value());
                            while (sits.hasNext()) {
                                sits.next();
                                if (sits.value().toString()=="file")
                                {
                                    sits.next();

                                    query.exec("SELECT @pp_id:=pp_id FROM math.program_param_list,math.program_param WHERE ppl_pp_id=pp_id and ppl_cp_id="+program_id+" and pp_name='"+sits.name()+"'");
                                    cout << program_id.toStdString() << " program id \n";
                                    query.prepare("INSERT INTO math.answer_param_value (pv_value, pv_pp_id) VALUES (:val, @pp_id);");
                                    query.bindValue(":val",sits.value().toString());
                                    query.exec();
                                    query.exec("SELECT @pv_id:=LAST_INSERT_ID();");
                                    query.exec("INSERT INTO math.answer_param_list (anpl_an_id, anpl_pv_id) VALUES (@an_id, @pv_id)");
                                    query.exec("SELECT BD_DATA FROM math.big_data where BD_ID="+sits.value().toString());
                                    query.next();
                                    file.setFileName(this->binaryPath+"/binaries/"+program_id+"/"+sits.value().toString());
                                    params<<this->binaryPath+"/binaries/"+program_id+"/"+sits.value().toString();
                                    if (file.open(QIODevice::WriteOnly | QIODevice::Text))
                                    {
                                        QTextStream out(&file);
                                        out << query.value(0).toByteArray();
                                    }
                                    file.close();
                                }
                            }
                        }
                        else {
                            params<<sit.value().toString();
                            query.exec("SELECT @pp_id:=pp_id FROM math.program_param_list,math.program_param WHERE ppl_pp_id=pp_id and ppl_cp_id="+program_id+" and pp_name='"+sit.name()+"'");
                            query.prepare("INSERT INTO math.answer_param_value (pv_value, pv_pp_id) VALUES (:val, @pp_id);");
                            query.bindValue(":val",sit.value().toString());
                            query.exec();
                            query.exec("SELECT @pv_id:=LAST_INSERT_ID();");
                            query.exec("INSERT INTO math.answer_param_list (anpl_an_id, anpl_pv_id) VALUES (@an_id, @pv_id)");
                        }
                    }
                }
            }
        }
    }
    QSqlDatabase::removeDatabase(conName);
    if (type=="execute")
    {
        if (params.at(0).isNull()||params.at(0).isEmpty())
        {
            socket.write("Nurodykite programa");
            socket.waitForBytesWritten();
        }
        else  emit this->requestExecute(params);
    }
    if (type=="compile")
    {
        if (params.at(0).isNull()||params.at(0).isEmpty())
        {
            socket.write("Nurodykite programa");
            socket.waitForBytesWritten();
        }
        else  emit this->requestCompile(params);
    }
    // qDebug()<<QString(data);
    socket.write(token.toLatin1());
    socket.flush();
    socket.waitForBytesWritten();
    socket.waitForDisconnected();
    socket.close();

}
Exemple #28
0
bool QgsHelp::urlExists( const QString &url )
{
  QUrl helpUrl( url );
  QTcpSocket socket;

  QgsSettings settings;
  bool proxyEnabled = settings.value( QStringLiteral( "proxy/proxyEnabled" ), false ).toBool();
  if ( proxyEnabled )
  {
    QNetworkProxy proxy;
    QString proxyHost = settings.value( QStringLiteral( "proxy/proxyHost" ), QString() ).toString();
    int proxyPort = settings.value( QStringLiteral( "proxy/proxyPort" ), QString() ).toString().toInt();
    QString proxyUser = settings.value( QStringLiteral( "proxy/proxyUser" ), QString() ).toString();
    QString proxyPassword = settings.value( QStringLiteral( "proxy/proxyPassword" ), QString() ).toString();

    QString proxyTypeString = settings.value( QStringLiteral( "proxy/proxyType" ), QString() ).toString();

    if ( proxyTypeString == QLatin1String( "DefaultProxy" ) )
    {
      QList<QNetworkProxy> proxies = QNetworkProxyFactory::systemProxyForQuery();
      if ( !proxies.isEmpty() )
      {
        proxy = proxies.first();
      }
    }
    else
    {
      QNetworkProxy::ProxyType proxyType = QNetworkProxy::DefaultProxy;
      if ( proxyTypeString == QLatin1String( "Socks5Proxy" ) )
      {
        proxyType = QNetworkProxy::Socks5Proxy;
      }
      else if ( proxyTypeString == QLatin1String( "HttpProxy" ) )
      {
        proxyType = QNetworkProxy::HttpProxy;
      }
      else if ( proxyTypeString == QLatin1String( "HttpCachingProxy" ) )
      {
        proxyType = QNetworkProxy::HttpCachingProxy;
      }
      else if ( proxyTypeString == QLatin1String( "FtpCachingProxy" ) )
      {
        proxyType = QNetworkProxy::FtpCachingProxy;
      }
      proxy = QNetworkProxy( proxyType, proxyHost, proxyPort, proxyUser, proxyPassword );
    }
    socket.setProxy( proxy );
  }

  socket.connectToHost( helpUrl.host(), 80 );
  if ( socket.waitForConnected() )
  {
    socket.write( "HEAD " + helpUrl.path().toUtf8() + " HTTP/1.1\r\n"
                  "Host: " + helpUrl.host().toUtf8() + "\r\n\r\n" );
    if ( socket.waitForReadyRead() )
    {
      QByteArray bytes = socket.readAll();
      if ( bytes.contains( "200 OK" ) ||  bytes.contains( "302 Found" ) )
      {
        return true;
      }
    }
  }

  return false;
}
Exemple #29
0
//--------------------------------------------------------------------
void tst_QIODevice::unget()
{
#if defined(Q_OS_WINCE) && defined(WINCE_EMULATOR_TEST)
    QSKIP("Networking tests in a WinCE emulator are unstable", SkipAll);
#endif
    QBuffer buffer;
    buffer.open(QBuffer::ReadWrite);
    buffer.write("ZXCV");
    buffer.seek(0);
    QCOMPARE(buffer.read(4), QByteArray("ZXCV"));
    QCOMPARE(buffer.pos(), qint64(4));

    buffer.ungetChar('a');
    buffer.ungetChar('b');
    buffer.ungetChar('c');
    buffer.ungetChar('d');

    QCOMPARE(buffer.pos(), qint64(0));

    char buf[6];
    QCOMPARE(buffer.readLine(buf, 5), qint64(4));
    QCOMPARE(buffer.pos(), qint64(4));
    QCOMPARE(static_cast<const char*>(buf), "dcba");

    buffer.ungetChar('a');
    buffer.ungetChar('b');
    buffer.ungetChar('c');
    buffer.ungetChar('d');

    QCOMPARE(buffer.pos(), qint64(0));

    for (int i = 0; i < 5; ++i) {
        buf[0] = '@';
        buf[1] = '@';
        QTest::ignoreMessage(QtWarningMsg,
                             "QIODevice::readLine: Called with maxSize < 2");
        QCOMPARE(buffer.readLine(buf, 1), qint64(-1));
        QCOMPARE(buffer.readLine(buf, 2), qint64(i < 4 ? 1 : -1));
        switch (i) {
        case 0:
            QCOMPARE(buf[0], 'd');
            break;
        case 1:
            QCOMPARE(buf[0], 'c');
            break;
        case 2:
            QCOMPARE(buf[0], 'b');
            break;
        case 3:
            QCOMPARE(buf[0], 'a');
            break;
        case 4:
            QCOMPARE(buf[0], '\0');
            break;
        }
        QCOMPARE(buf[1], i < 4 ? '\0' : '@');
    }

    buffer.ungetChar('\n');
    QCOMPARE(buffer.readLine(), QByteArray("\n"));

    buffer.seek(1);
    buffer.readLine(buf, 3);
    QCOMPARE(static_cast<const char*>(buf), "XC");

    buffer.seek(4);
    buffer.ungetChar('Q');
    QCOMPARE(buffer.readLine(buf, 3), qint64(1));

    for (int i = 0; i < 2; ++i) {
        QTcpSocket socket;
        QIODevice *dev;
        QByteArray result;
        const char *lineResult;
        if (i == 0) {
            dev = &buffer;
            result = QByteArray("ZXCV");
            lineResult = "ZXCV";
        } else {
            socket.connectToHost(QtNetworkSettings::serverName(), 80);
            socket.write("GET / HTTP/1.0\r\n\r\n");
            QVERIFY(socket.waitForReadyRead());
            dev = &socket;
            result = QByteArray("HTTP");
            lineResult = "Date";
        }
        char ch, ch2;
        dev->seek(0);
        dev->getChar(&ch);
        dev->ungetChar(ch);
        QCOMPARE(dev->peek(4), result);
        dev->getChar(&ch);
        dev->getChar(&ch2);
        dev->ungetChar(ch2);
        dev->ungetChar(ch);
        QCOMPARE(dev->read(1), result.left(1));
        QCOMPARE(dev->read(3), result.right(3));

        if (i == 0)
            dev->seek(0);
        else
            dev->readLine();
        dev->getChar(&ch);
        dev->ungetChar(ch);
        dev->readLine(buf, 5);
        QCOMPARE(static_cast<const char*>(buf), lineResult);

        if (i == 1)
            socket.close();
    }
}
void getCoarseningInfo(int32NDArray& coarseningInfo, const QString &hostName, quint16 port, const qint64& caseId)
{
    QString serverName = hostName;
    quint16 serverPort = port;

    QTcpSocket socket;
    socket.connectToHost(serverName, serverPort);

    if (!socket.waitForConnected(riOctavePlugin::connectTimeOutMilliSecs))
    {
        error((("Connection: ") + socket.errorString()).toLatin1().data());
        return;
    }

    // Create command and send it:

    QString command = QString("GetCoarseningInfo %1").arg(caseId);
    QByteArray cmdBytes = command.toLatin1();

    QDataStream socketStream(&socket);
    socketStream.setVersion(riOctavePlugin::qtDataStreamVersion);

    socketStream << (qint64)(cmdBytes.size());
    socket.write(cmdBytes);

    // Get response. First wait for the header

    while (socket.bytesAvailable() < (int)(sizeof(quint64)))
    {
        if (!socket.waitForReadyRead(riOctavePlugin::longTimeOutMilliSecs))
        {
            error((("Waiting for header: ") + socket.errorString()).toLatin1().data());
            return;
        }
    }

    quint64 byteCount;
    socketStream >> byteCount;

    quint64 boxCount = byteCount / (6 * sizeof(qint32));

    dim_vector dv (1, 1);
    dv(0) = boxCount;
    dv(1) = 6;

    coarseningInfo.resize(dv);

    for (size_t i = 0; i < boxCount; i++)
    {
        qint32 i1;
        qint32 i2;
        qint32 j1;
        qint32 j2;
        qint32 k1;
        qint32 k2;

        socketStream >> i1;
        socketStream >> i2;
        socketStream >> j1;
        socketStream >> j2;
        socketStream >> k1;
        socketStream >> k2;

        coarseningInfo(i, 0) = i1;
        coarseningInfo(i, 1) = i2;
        coarseningInfo(i, 2) = j1;
        coarseningInfo(i, 3) = j2;
        coarseningInfo(i, 4) = k1;
        coarseningInfo(i, 5) = k2;
    }

    return;
}