Example #1
0
void HttpDaemon::incomingConnection(qintptr socket)
{
    qDebug() << "incoming connection";
    if (disabled)
        return;

    // When a new client connects, the server constructs a QTcpSocket and all
    // communication with the client is done over this QTcpSocket. QTcpSocket
    // works asynchronously, this means that all the communication is done
    // in the two slots readClient() and discardClient().
    QTcpSocket* s = new QTcpSocket(this);
    connect(s, SIGNAL(readyRead()), this, SLOT(readClient()));
    connect(s, SIGNAL(disconnected()), this, SLOT(discardClient()));
    s->setSocketDescriptor(socket);

}
Example #2
0
/* 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);
}
Example #3
0
void ApiServer::incomingConnection(int socketDescriptor)
{
    QTcpSocket *client = new QTcpSocket(this);
    client->setSocketDescriptor(socketDescriptor);

    ClientInfo cs;
    cs.isAuthorized = false;

    m_clients.insert(client, cs);

    client->write(ApiVersion);

    DEBUG_LOW_LEVEL << "Incoming connection from:" << client->peerAddress().toString();

    connect(client, SIGNAL(readyRead()), this, SLOT(clientProcessCommands()));
    connect(client, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));
}
Example #4
0
void CollaborativeSchemaServer::slot_newIncommingConnection( int socketDescriptor )
{
    QTcpSocket* tcpSocket = new QTcpSocket();

	bool result = tcpSocket->setSocketDescriptor( socketDescriptor );
    if( false == result )
    {
        logError( this, QString("failed to set socket descriptor: %1").arg(tcpSocket->errorString()) );
        delete tcpSocket;
        return;
    }
    
    logInfo( this, QString("new client [%1:%2]").arg(tcpSocket->peerAddress().toString()).arg(tcpSocket->peerPort()), true );
    connect( tcpSocket, SIGNAL(readyRead()), this, SLOT(slot_IncommingData()) );
    connect( tcpSocket, SIGNAL(disconnected()), this, SLOT(slot_ClientDiconnected()) );
    
    _clients.append( tcpSocket );
}
Example #5
0
void TCPThread::run() {
    QTcpSocket tcpSocket;
    if (!tcpSocket.setSocketDescriptor(socketDescriptor_)) {
        emit error(tcpSocket.error());
        return;
    }

    qint64 x = 0;
    while(x < data.size()){
        qint64 y= tcpSocket.write(data);
        x+= y;
        qDebug()<< x << " to: " << socketDescriptor_;
    }

    tcpSocket.disconnectFromHost();
    tcpSocket.waitForDisconnected();


}
Example #6
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);
  }
}
 void UekiAccessServerThread::run()
 {
     QTcpSocket tcpSocket;
     if (!tcpSocket.setSocketDescriptor(socketDescriptor)) {
         emit error(tcpSocket.error());
         return;
     }

     QByteArray block;
     QDataStream out(&block, QIODevice::WriteOnly);
     out.setVersion(QDataStream::Qt_4_0);
     out << (quint16)0;
     out.device()->seek(0);
     out << (quint16)(block.size() - sizeof(quint16));

     tcpSocket.write(block);
     tcpSocket.disconnectFromHost();
     tcpSocket.waitForDisconnected();
 }
Example #8
0
//! [1]
void FortuneThread::run()
{
    QTcpSocket tcpSocket;
//! [1] //! [2]
    if (!tcpSocket.setSocketDescriptor(socketDescriptor)) {
        emit error(tcpSocket.error());
        return;
    }
//! [2] //! [3]

    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_0);
    out << text;
//! [3] //! [4]

    tcpSocket.write(block);
    tcpSocket.disconnectFromHost();
    tcpSocket.waitForDisconnected();
}
Example #9
0
bool QWebProcessor::newConnection(qint16 port, qintptr socketDescriptor)
{
    qDebug()<<"QWebProcessor->newConnection()"<<socketDescriptor<<QTime::currentTime().toString();
    if (socket)
    {
        QTcpSocket *sock = new QTcpSocket();
        sock->setSocketDescriptor(socketDescriptor);
        sock->close();
        sock->deleteLater();
        return true;
    }else
    {
        this->port = port;
        socket = new QTcpSocket();
        connect(socket, SIGNAL(readyRead()), this, SLOT(socketRead()));
        connect(socket, SIGNAL(disconnected()), this, SLOT(onSocketDisconnected()));
        socket->setSocketDescriptor(socketDescriptor);
        return true;
    }
}
Example #10
0
void QxThread::doProcess(QTcpSocket & socket)
{
    if (! socket.setSocketDescriptor(m_iSocketDescriptor))
    {
        Q_EMIT error("[QxOrm] invalid socket descriptor : cannot start transaction", QxTransaction_ptr());
        return;
    }

    qx_bool bReadOk = readSocket(socket);
    if (! bReadOk) {
        Q_EMIT error(QString("[QxOrm] unable to read request from socket : '") + bReadOk.getDesc() + QString("'"), QxTransaction_ptr());
        return;
    }
    if (! m_bIsRunning) {
        return;
    }

    Q_EMIT transactionStarted(m_pTransaction);
    try {
        m_pTransaction->executeServer();
    }
    catch (const qx::exception & x) {
        qx_bool xb = x.toQxBool();
        m_pTransaction->setMessageReturn(xb);
    }
    catch (const std::exception & e) {
        m_pTransaction->setMessageReturn(qx_bool(QX_ERROR_UNKNOWN, e.what()));
    }
    catch (...) {
        m_pTransaction->setMessageReturn(qx_bool(QX_ERROR_UNKNOWN, "unknown error"));
    }
    if (! m_bIsRunning) {
        return;
    }

    qx_bool bWriteOk = writeSocket(socket);
    if (! bWriteOk) {
        Q_EMIT error(QString("[QxOrm] unable to write reply to socket : '") + bWriteOk.getDesc() + QString("'"), m_pTransaction);
    }
    Q_EMIT transactionFinished(m_pTransaction);
}
Example #11
0
File: server.cpp Project: vos/qcc
void Server::incomingConnection(int socketDescriptor)
{
    QTcpSocket *socket = new QTcpSocket(this);
    socket->setSocketDescriptor(socketDescriptor);
    addPendingConnection(socket);

#ifdef DEBUG
    qDebug("\nServer::incomingConnection(%i): %s:%i", socketDescriptor,
           qPrintable(socket->peerAddress().toString()), socket->peerPort());
#endif

    connect(socket, SIGNAL(disconnected()), SLOT(client_disconnected()));
    connect(socket, SIGNAL(readyRead()), SLOT(client_readyRead()));

    m_clients.insert(socket, new Client);
    QccPacket(QccPacket::ConnectionAccepted).send(socket); // QccPacket::ConnectionRefused

#ifdef DEBUG
    qDebug("ConnectionAccepted");
#endif
}
Example #12
0
void TcpSockets::incoming(qintptr ID)
{
  QTcpSocket* socket = new QTcpSocket();

  while( SClients.isEmpty() == false )
  {
    SClients[ SClients.lastKey() ]->close();
    SClients.remove( SClients.lastKey() );
  }

  if(!socket->setSocketDescriptor(ID))
  {
    emit error(socket->error());
        qDebug() << "error";
    return;
  }

  SClients[ID]=socket;
  connect(SClients[ID],SIGNAL(readyRead()),this, SLOT(slotReadClient()));

}
void TcpServer::incomingConnection(qintptr socketDescriptor) //多线程必须在此函数里捕获新连接.
{
    if (tcpClient->size() > maxPendingConnections())//继承重写此函数后,QTcpServer默认的判断最大连接数失效,自己实现
    {
        QTcpSocket tcp;
        tcp.setSocketDescriptor(socketDescriptor);
        tcp.disconnectFromHost();
        return;
    }
    auto th = ThreadHandle::getClass().getThread();
    auto tcpTemp = new TcpSocket(socketDescriptor);
    QString ip =  tcpTemp->peerAddress().toString();
    qint16 port = tcpTemp->peerPort();

    connect(tcpTemp,&TcpSocket::sockDisConnect,this,&TcpServer::sockDisConnectSlot);//NOTE:断开连接的处理,从列表移除,并释放断开的Tcpsocket,此槽必须实现,线程管理计数也是考的他
    connect(this,&TcpServer::sentDisConnect,tcpTemp,&TcpSocket::disConTcp);//断开信号

    tcpTemp->moveToThread(th);//把tcp类移动到新的线程,从线程管理类中获取
    tcpClient->insert(socketDescriptor,tcpTemp);//插入到连接信息中
    emit connectClient(socketDescriptor,ip,port);
}
Example #14
0
void BatchSender::run()
{
    QTcpSocket tcpSocket;
    qDebug() << "----- Thread Id in doWork(): " << thread()->currentThreadId();
//    QObject::connect(tcpSocket,SIGNAL(bytesWritten(qint64)),this,SLOT(keepTrack(qint64)));
    timer.start();
    if (!tcpSocket.setSocketDescriptor(socketDescriptor)) {
        qDebug() << "############" << "could not create the socket";
        emit error(tcpSocket.error());
        return;
    }

    qDebug() << "client address: " <<tcpSocket.peerAddress().toString();


    QFile file("batch.tar");
    file.open(QIODevice::ReadOnly);
    QByteArray tarBlock = file.readAll();

    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_0);

    out << (quint32)tarBlock.size();
    totalBytes = (quint32)tarBlock.size() + 4;
    block.append(tarBlock);
    int createTime = timer.elapsed();
    qDebug() << "--- time to create buffer batch: " <<createTime;
//    mutex.lock();
    int numWrite = tcpSocket.write(block);
    tcpSocket.flush();
    while(tcpSocket.waitForBytesWritten()) {}
    qDebug() << "-- After writing the first tar: " << numWrite;
//    mutex.unlock();

    file.close();
    QThread::msleep(60000);
}
Example #15
0
	QTcpSocket* SocketServer::nextPendingConnection()
	{
		// Initialise socket address structure
		sockaddr_un sa;
		socklen_t len = sizeof(sa);
		::memset(&sa, 0, len);

		// Listen on the socket
		d->lockSocket(d->m_socket);
		const int newSocket = ::accept(d->m_socket, reinterpret_cast<sockaddr*>(&sa), &len);
		d->releaseSocket(d->m_socket);

		if(newSocket == -1 && (errno == EAGAIN || errno == EWOULDBLOCK))
		{
			return 0;
		}
		else
		{
			QTcpSocket* socket = new QTcpSocket(this);
			socket->setSocketDescriptor(newSocket);
			return socket;
		}
	}
Example #16
0
void AdminServerTask::run() {
    QTcpSocket tcpSocket;
       
    if (!tcpSocket.setSocketDescriptor(taskSocketDescriptor)) {
        QLogger(QLogger::INFO_SYSTEM, QLogger::LEVEL_ERROR) << __FUNCTION__ << "Error converting socket descriptor to socket:" << tcpSocket.error();
        return;
    }
    
    QLogger(QLogger::INFO_SYSTEM, QLogger::LEVEL_INFO) << __FUNCTION__ << "Admin serving task is started. Agent ip:" <<
                                                          tcpSocket.peerAddress().toString() << ":" << tcpSocket.peerPort();

    commandExecutor = new AdminCommandExecutor();
    Q_ASSERT(commandExecutor != NULL);
    
    // Read and parse commands from socket
    packetsReadLoop(&tcpSocket);
    
    delete commandExecutor;
    commandExecutor = NULL;
    
    // Ending connection
    socketDisconnect(&tcpSocket);
}
Example #17
0
void HttpServer::incomingConnection(int socketDescriptor)
{
  QTcpSocket *serverSocket;
#ifndef QT_NO_OPENSSL
  if (m_https)
    serverSocket = new QSslSocket(this);
  else
#endif
    serverSocket = new QTcpSocket(this);
  if (serverSocket->setSocketDescriptor(socketDescriptor)) {
#ifndef QT_NO_OPENSSL
    if (m_https) {
      static_cast<QSslSocket*>(serverSocket)->setProtocol(QSsl::AnyProtocol);
      static_cast<QSslSocket*>(serverSocket)->setPrivateKey(m_key);
      static_cast<QSslSocket*>(serverSocket)->setLocalCertificate(m_certificate);
      static_cast<QSslSocket*>(serverSocket)->startServerEncryption();
    }
#endif
    handleNewConnection(serverSocket);
  } else {
    serverSocket->deleteLater();
  }
}
Example #18
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
}
    void         createSocket(qintptr sokDesc, TBackend bend) {
        isocket.ibackendType = bend;

        if        ( bend == ETcpSocket ) {
            QTcpSocket* sok    = new QTcpSocket( q_func() );
            isocket.itcpSocket = sok;
            sok->setSocketDescriptor(sokDesc);

            QObject::connect(sok,       &QTcpSocket::readyRead, [this](){
                onReadyRead();
            });
            QObject::connect(sok,       &QTcpSocket::bytesWritten, [this](){
                if ( isocket.itcpSocket->bytesToWrite() == 0  &&  ilastResponse )
                    emit ilastResponse->allBytesWritten();
            });
            QObject::connect(sok,       &QTcpSocket::disconnected,
                             q_func(),  &QHttpConnection::disconnected,
                             Qt::QueuedConnection);

        } else if ( bend == ELocalSocket ) {
            QLocalSocket* sok    = new QLocalSocket( q_func() );
            isocket.ilocalSocket = sok;
            sok->setSocketDescriptor(sokDesc);

            QObject::connect(sok,       &QLocalSocket::readyRead, [this](){
                onReadyRead();
            });
            QObject::connect(sok,       &QLocalSocket::bytesWritten, [this](){
                if ( isocket.ilocalSocket->bytesToWrite() == 0  &&  ilastResponse )
                    emit ilastResponse->allBytesWritten();
            });
            QObject::connect(sok,       &QLocalSocket::disconnected,
                             q_func(),  &QHttpConnection::disconnected,
                             Qt::QueuedConnection);
        }

    }
Example #20
0
//HTTP reception
void InterfaceHttpServer::incomingConnection(int socketDescriptor) {
    QTcpSocket *socket = new QTcpSocket(this);
    connect(socket, SIGNAL(readyRead()),    this, SLOT(readClient()));
    connect(socket, SIGNAL(disconnected()), this, SLOT(discardClient()));
    socket->setSocketDescriptor(socketDescriptor);
}
Example #21
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();

}
Example #22
0
QAbstractSocket* TcpSocketCreation::operator()() const {
	QTcpSocket* socket = new QTcpSocket();
	socket->setSocketDescriptor(socketDescriptor);
	return socket;
}
Example #23
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();


}
Example #24
0
void FileServerThread::run()    //TODO: use mutexes
{
    QString filename;
    QString ID;
    QFile file;
    QTcpSocket socket;
    socket.setSocketDescriptor (m_descriptor);

    while (!m_doQuit) {
        m_status = Waiting;
        while (!socket.bytesAvailable() && !m_doQuit) {
            socket.waitForReadyRead();
        }
        if (m_doQuit)
            break;

        QString data (socket.readAll());

        if (!Kapotah::TransferManager::instance()->pathForId (data).isEmpty()) {
            setStatus(PreparingToSend);
            ID = data;
            filename = Kapotah::TransferManager::instance()->pathForId (data);

            file.setFileName (filename);

            if (!file.open (QIODevice::ReadOnly)) {
                setStatus(ErrorFileNotFound);
                break;
            }

            socket.write ("OK");
            socket.waitForBytesWritten();
            emit startedTransfer (ID);
            setStatus(Sending);

            while (!file.atEnd() && !m_doQuit) {
                if (socket.state() != QTcpSocket::ConnectedState) {
                    emit finishedTransfer (ID);
                    setStatus(Finished);
                    break;
                }

                socket.write (file.read (s_bytesPerBlock));
                socket.waitForBytesWritten();

                while (socket.bytesToWrite())
                    socket.flush();

                emit transferProgress (ID, file.pos() / file.size() *100);
            }

            file.close();

            if (m_doQuit) {
                setStatus(Canceled);
                emit canceledTransfer(ID);
                socket.disconnectFromHost();
            } else {
                setStatus(Finished);
                emit finishedTransfer (ID);
            }

            socket.waitForDisconnected ();
            break;
        } else {
            setStatus(ErrorIDNotFound);
            emit transferNotFound(ID);
            break;
        }

        deleteLater();
    }
}
Example #25
0
void OnoffDownloadServerSession::run()
{
    LOG_INFO("Beginning of OnoffDownloadServerSession::run");
    
    QTcpSocket socket;
    if( !socket.setSocketDescriptor(m_socketDescriptor))
    {
        LOG_ERROR("Cannot set socket descriptor");
    }

    // Receive request
    qint16 fillSize;
    qint32 onTime;
    qint32 maxRate;
    qint16 packetSize;
    
    while( socket.bytesAvailable() < 12 )
    {
        if( !socket.waitForReadyRead(3 * 1000))
        {
            LOG_INFO("OnoffDownload session timed out");
            return;
        }
    }

    QDataStream in(&socket);
    in >> fillSize >> onTime >> maxRate >> packetSize;
    
    // Receive filled bytes in the request
    while( socket.bytesAvailable() < fillSize )
    {
        if( !socket.waitForReadyRead(3 * 1000))
        {
            LOG_INFO("OnoffDownload session timed out");
            return;
        }
    }
    
    // Send data
    qint64 totalBytes = 0;
    QByteArray block(packetSize, 0);
    QTime t;
    t.start();

    while( t.elapsed() < onTime )
    {
        qint32 bytesSent = (qint32)socket.write(block);
        totalBytes += bytesSent;
        socket.waitForBytesWritten(-1);

        if( socket.state() == QAbstractSocket::UnconnectedState )
        {
            break;
        }
        
        // LOG_DEBUG("OnoffDownloadServerSession %d / %d", 
        //    (int)bytesSent, (int)totalBytes);
        
        // Rate limit
        if( maxRate != -1 && totalBytes * 1000 / maxRate > (qint64)t.elapsed())
        {
            msleep(qMax((int)(totalBytes * 1000 / maxRate - t.elapsed()), 0));
        }
    }

    // Close connection
    socket.close();
    LOG_INFO("End of OnoffDownloadServerSession::run");
}
Example #26
0
void ServerPool::newTcpConnection(int socket)
{
    QTcpSocket *qsock = new QTcpSocket(this);
    qsock->setSocketDescriptor(socket);
    emit newConnection(qsock);
}