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."; }
void lsLogServitemThreated::run() { QTcpSocket tcpSocket; if (!tcpSocket.setSocketDescriptor(socketDescriptor)) { emit error(tcpSocket.error()); return; } while ( tcpSocket.isOpen() ) { QByteArray block; QDataStream out(&block, QIODevice::WriteOnly); out.setVersion(QDataStream::Qt_4_0); out << (quint16)0; out << text; text.clear(); out.device()->seek(0); out << (quint16)(block.size() - sizeof(quint16)); tcpSocket.write(block); tcpSocket.flush(); while ( tcpSocket.isOpen() && text.isEmpty() ) { msleep(100); } } tcpSocket.disconnectFromHost(); tcpSocket.waitForDisconnected(); }
void ClientThread::run() { QTcpSocket tcpSocket; if (!tcpSocket.setSocketDescriptor(m_socketDescriptor)) { qWarning() << ":((("; emit error(tcpSocket.error()); return; } m_running = true; QString command, response; // Send greetings tcpSocket.write("OK MPD 0.12.2\n"); while (m_running && (tcpSocket.state() == QAbstractSocket::ConnectedState)) { m_running = tcpSocket.waitForReadyRead(); // Wait for command, // if none is received until timeout // (default 30 seconds, stop running). command = QString(tcpSocket.readLine()).trimmed(); qDebug() << command; tcpSocket.write(parseCommand(command).toLocal8Bit()); } tcpSocket.disconnectFromHost(); }
void SendThread::run() { QTcpSocket client; qDebug() << "Thread Descriptor :" << socketDescriptor; if (!client.setSocketDescriptor(socketDescriptor)) { qDebug() << client.error(); return; } qDebug() << "Thread : Connected"; //send File QFile inputFile(FILENAME); QByteArray read; inputFile.open(QIODevice::ReadOnly); while(1) { read.clear(); read = inputFile.read(32768*8); qDebug() << "Read : " << read.size(); if(read.size()==0) break; qDebug() << "Written : " << client.write(read); client.waitForBytesWritten(); read.clear(); } inputFile.close(); client.disconnectFromHost(); client.waitForDisconnected(); qDebug() << "Thread : File transfer completed"; }
void ClientSktTcp::error() { QTcpSocket* s = qobject_cast<QTcpSocket*>(sender()); show(QString("TCP socket error %1, %2").arg(s->error()).arg(s->errorString())); unplug(); }
void ServerSktTcp::error() { QTcpSocket* s = qobject_cast<QTcpSocket*>(sender()); show(QString("TCP socket error %1, %2").arg(s->error()).arg(s->errorString())); s->deleteLater(); }
/*------------------------------------------------------------------------------* *------------------------------------------------------------------------------*/ void WebProxy::closeConnection() { QTcpSocket *proxySocket = qobject_cast<QTcpSocket*>(sender()); if (proxySocket) { QTcpSocket *socket = qobject_cast<QTcpSocket*>(proxySocket->parent()); if (socket) socket->disconnectFromHost(); if (proxySocket->error() != QTcpSocket::RemoteHostClosedError) qWarning() << "Error for:" << proxySocket->property("url").toUrl() << proxySocket->errorString(); proxySocket->deleteLater();; } } //WebProxy::closeConnection
/*! \internal */ void QInterProcessChannel::check() { //qDebug("checking connection..."); QTcpSocket *pSocket = new QTcpSocket(this); pSocket->connectToHost(m_addr, m_port); if ( pSocket->error() != -1 ) { emit connectionLost(); return; } pSocket->waitForConnected(WAIT_TIMEOUT); if ( pSocket->error() != -1 ) { emit connectionLost(); return; } }
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(); }
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(); }
//! [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(); }
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 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); }
void HttpServerThread::run() { m_server = new BlockingHttpServer(m_features & Ssl); m_server->listen(); QMutexLocker lock(&m_mutex); m_port = m_server->serverPort(); lock.unlock(); m_ready.release(); const bool doDebug = qgetenv("KDSOAP_DEBUG").toInt(); if (doDebug) qDebug() << "HttpServerThread listening on port" << m_port; // Wait for first connection (we'll wait for further ones inside the loop) QTcpSocket *clientSocket = m_server->waitForNextConnectionSocket(); Q_ASSERT(clientSocket); Q_FOREVER { // get the "request" packet if (doDebug) { qDebug() << "HttpServerThread: waiting for read"; } if (clientSocket->state() == QAbstractSocket::UnconnectedState || !clientSocket->waitForReadyRead(2000)) { if (clientSocket->state() == QAbstractSocket::UnconnectedState) { delete clientSocket; if (doDebug) { qDebug() << "Waiting for next connection..."; } clientSocket = m_server->waitForNextConnectionSocket(); Q_ASSERT(clientSocket); continue; // go to "waitForReadyRead" } else { qDebug() << "HttpServerThread:" << clientSocket->error() << "waiting for \"request\" packet"; break; } } const QByteArray request = m_partialRequest + clientSocket->readAll(); if (doDebug) { qDebug() << "HttpServerThread: request:" << request; } // Split headers and request xml lock.relock(); const bool splitOK = splitHeadersAndData(request, m_receivedHeaders, m_receivedData); if (!splitOK) { //if (doDebug) // qDebug() << "Storing partial request" << request; m_partialRequest = request; continue; } m_headers = parseHeaders(m_receivedHeaders); if (m_headers.value("Content-Length").toInt() > m_receivedData.size()) { //if (doDebug) // qDebug() << "Storing partial request" << request; m_partialRequest = request; continue; } m_partialRequest.clear(); if (m_headers.value("_path").endsWith("terminateThread")) // we're asked to exit break; // normal exit // TODO compared with expected SoapAction QList<QByteArray> contentTypes = m_headers.value("Content-Type").split(';'); if (contentTypes[0] == "text/xml" && m_headers.value("SoapAction").isEmpty()) { qDebug() << "ERROR: no SoapAction set for Soap 1.1"; break; }else if( contentTypes[0] == "application/soap+xml" && !contentTypes[2].startsWith("action")){ qDebug() << "ERROR: no SoapAction set for Soap 1.2"; break; } lock.unlock(); //qDebug() << "headers received:" << m_receivedHeaders; //qDebug() << headers; //qDebug() << "data received:" << m_receivedData; if (m_features & BasicAuth) { QByteArray authValue = m_headers.value("Authorization"); if (authValue.isEmpty()) authValue = m_headers.value("authorization"); // as sent by Qt-4.5 bool authOk = false; if (!authValue.isEmpty()) { //qDebug() << "got authValue=" << authValue; // looks like "Basic <base64 of user:pass>" Method method; QString headerVal; parseAuthLine(QString::fromLatin1(authValue.data(),authValue.size()), &method, &headerVal); //qDebug() << "method=" << method << "headerVal=" << headerVal; switch (method) { case None: // we want auth, so reject "None" break; case Basic: { const QByteArray userPass = QByteArray::fromBase64(headerVal.toLatin1()); //qDebug() << userPass; // TODO if (validateAuth(userPass)) { if (userPass == ("kdab:testpass")) { authOk = true; } break; } default: qWarning("Unsupported authentication mechanism %s", authValue.constData()); } } if (!authOk) { // send auth request (Qt supports basic, ntlm and digest) const QByteArray unauthorized = "HTTP/1.1 401 Authorization Required\r\nWWW-Authenticate: Basic realm=\"example\"\r\nContent-Length: 0\r\n\r\n"; clientSocket->write( unauthorized ); if (!clientSocket->waitForBytesWritten(2000)) { qDebug() << "HttpServerThread:" << clientSocket->error() << "writing auth request"; break; } continue; } } // send response QByteArray response = makeHttpResponse(m_dataToSend); if (doDebug) { qDebug() << "HttpServerThread: writing" << response; } clientSocket->write(response); clientSocket->flush(); } // all done... delete clientSocket; delete m_server; if (doDebug) { qDebug() << "HttpServerThread terminated"; } }
//! [4] void FortuneThread::run() { mutex.lock(); //! [4] //! [5] QString serverName = hostName; quint16 serverPort = port; mutex.unlock(); //! [5] //! [6] while (!quit) { //! [7] const int Timeout = 5 * 1000; QTcpSocket socket; socket.connectToHost(serverName, serverPort); //! [6] //! [8] if (!socket.waitForConnected(Timeout)) { emit error(socket.error(), socket.errorString()); return; } //! [8] //! [9] while (socket.bytesAvailable() < (int)sizeof(quint16)) { if (!socket.waitForReadyRead(Timeout)) { emit error(socket.error(), socket.errorString()); return; } //! [9] //! [10] } //! [10] //! [11] quint16 blockSize; QDataStream in(&socket); in.setVersion(QDataStream::Qt_4_0); in >> blockSize; //! [11] //! [12] while (socket.bytesAvailable() < blockSize) { if (!socket.waitForReadyRead(Timeout)) { emit error(socket.error(), socket.errorString()); return; } //! [12] //! [13] } //! [13] //! [14] mutex.lock(); QString fortune; in >> fortune; emit newFortune(fortune); //! [7] //! [14] //! [15] cond.wait(&mutex); serverName = hostName; serverPort = port; mutex.unlock(); } //! [15] }
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(); }
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); }