int UCHome_Main_SiteConst::fetchFeedData() { q_debug()<<"impled"; QTcpSocket *sock = NULL; sock = new QTcpSocket(); sock->connectToHost(this->host, this->port); if(!sock->waitForConnected()) { q_debug()<<"Connect error"; return FETCH_FEED_ERROR; } QString request; request = QString( "GET %1 HTTP/1.1\r\n" "Host: uchome.developer.manyou.com\r\n" "User-Agent: Opera/9.62 (X11; Linux i686; U; zh-cn)\r\n" "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n" "Accept-Language: zh-cn,zh;q=0.5\r\n" "Accept-Charset: gb2312,utf-8;q=0.7,*;q=0.7\r\n" //"Keep-Alive: 300\r\n" //"Connection: keep-alive\r\n" "Connection: close\r\n" "Cookie: %2\r\n" "\r\n" ) .arg(this->feed_url, this->cookies); q_debug()<<request; sock->write(request.toAscii()); if(!sock->waitForBytesWritten()) { q_debug()<<"Write error"; return FETCH_FEED_ERROR; } char header[8192] = {0} ; char b2[2] = {0}; char *bp = &header[0]; char *tp = bp; qint64 rlen = 0; qint64 oklen = 0; if(!sock->waitForReadyRead()) { q_debug()<<"wait read error"; return LOGIN_ERROR; } while(true) { oklen = sock->bytesAvailable(); if(oklen < 0 ) { q_debug()<<"wait read errorsdfjsdifsdifsdifj"; } while(oklen-- > 0) { rlen = sock->read(b2, 1); *tp++ = b2[0]; if(tp - bp > 4 && strncmp(tp-4, "\r\n\r\n", 4) == 0) { break; } } if(strncmp(tp-4, "\r\n\r\n", 4) == 0) { break; } } //parse header, got file length QString html_header = header; QStringList header_lines = QString(header).split("\r\n"); qint64 content_length = -1; for(int i = 0; i < header_lines.count(); i ++) { if(header_lines.at(i).startsWith("Content-length")) { content_length = header_lines.at(i).split(":").at(1).trimmed().toLongLong(); } } if(content_length == -1) { q_debug()<<"Unknown content-length for header:"<< html_header; //return FETCH_FEED_ERROR; } QByteArray html; QByteArray hb ; while(true) { oklen = sock->bytesAvailable(); if(oklen > 0) { hb= sock->readAll(); html += hb; }else if(oklen == 0) { if(!sock->waitForReadyRead()) { q_debug()<<"wait read error"; break; } }else{ q_debug()<<"bytesAvalibale < 0"; break; } } this->feed_page_html = html; q_debug()<<"read len =? content-length: "<<html.length()<<" =? "<<content_length; q_debug()<<html.left(6)<<html.right(20); this->clean_my_name_lable(); return FETCH_FEED_OK; }
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(); } }
/** A file is requested by the host * * This function is called when the client retirieve a file. The file * is sent to the client from the \c uploaded directory. * * \param filename The filename without path * */ void RainbruRPG::Network::Ftp::FtpTransfer:: commandRETR(const QString& filename){ LOGI("Sending file..."); QString s("Sending file "); s+=filename; emit(log(s)); LOGI(s.toLatin1()); nextCommand=FTC_RETR; // Get the absolute filename GlobalURI gu; std::string stdFilename(filename.toLatin1()); std::string fullFileName=gu.getUploadFile(stdFilename); nextFilename=filename; nextOnlyFilename=filename; LOGCATS("Opening file '"); LOGCATS(fullFileName.c_str()); LOGCAT(); QFile f(fullFileName.c_str()); QIODevice::OpenMode om; // We are in Binary mode if (transferType==FTT_BINARY){ om=QIODevice::ReadOnly; } // We are in ASCII mode else if (transferType==FTT_ASCII){ om=QIODevice::ReadOnly|QIODevice::Text; } if(f.open(om)){ QTcpSocket sock; if (waitForConnection(&sock)){ emit(startTransferFile(filename, f.size())); int rep=0; while (!f.atEnd()){ rep=sock.write(f.read(MAX_READ_LENGTH)); if (rep==-1){ LOGE("An error occured during RETR command"); break; } else{ LOGCATS("Writing "); LOGCATI(rep); LOGCATS(" bytes"); LOGCAT(); sock.waitForBytesWritten(3000); } } // Transfer complete emit(log("Transfer channel closed")); emit(transferComplete(filename)); sock.disconnectFromHost(); LOGI("Transfer complete"); f.close(); } } else{ emit(log("An error occured during opening file :")); QFile::FileError fe=f.error(); QString feText; if (fe==QFile::OpenError){ feText=("5 The file could not be opened."); } else{ feText.setNum(fe); } emit(log(feText)); } }
int UCHome_Main_SiteConst::login() { QTcpSocket *sock = NULL; sock = new QTcpSocket(); sock->connectToHost(this->host, this->port); if(!sock->waitForConnected()) { q_debug()<<"error:"; return LOGIN_ERROR; } QString data ; data = QString("username=%1&password=%2&cookietime=315360000&refer=space.php%3Fdo%3Dhome&loginsubmit=%B5%C7%C2%BC&formhash=3040598c").arg(this->username, this->password) ; QString request; request = QString("POST /uchome/do.php?ac=login&&ref HTTP/1.1\r\n" "Host: uchome.developer.manyou.com\r\n" "User-Agent: Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.0.4) Gecko/2008112913 Gentoo Minefield/3.0.4\r\n" "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n" "Accept-Language: zh-cn,zh;q=0.5\r\n" "Accept-Charset: gb2312,utf-8;q=0.7,*;q=0.7\r\n" "Keep-Alive: 300\r\n" "Connection: keep-alive\r\n" "Referer: http://uchome.developer.manyou.com/uchome/index.php\r\n" "Content-Type: application/x-www-form-urlencoded\r\n" "Content-Length: %1\r\n\r\n") .arg(data.length()); ; request += data; q_debug()<<request; sock->write(request.toAscii()); if(!sock->waitForBytesWritten()) { q_debug()<<"write error"; return LOGIN_ERROR; } char header[8192] = {0} ; char b2[2] = {0}; char *bp = &header[0]; char *tp = bp; qint64 rlen = 0; qint64 oklen = 0; while(true) { if(!sock->waitForReadyRead()) { q_debug()<<"wait read error"; return LOGIN_ERROR; } oklen = sock->bytesAvailable(); if(oklen < 0 ) { q_debug()<<"wait read errorsdfjsdifsdifsdifj"; } while(oklen-- > 0) { rlen = sock->read(b2, 1); *tp++ = b2[0]; if(tp - bp > 4 && strncmp(tp-4, "\r\n\r\n", 4) == 0) { break; } } if(strncmp(tp-4, "\r\n\r\n", 4) == 0) { break; } } //parse header, got file length QStringList cookie_lines; QStringList header_lines = QString(header).split("\r\n"); qint64 content_length = -1; for(int i = 0; i < header_lines.count(); i ++) { if(header_lines.at(i).startsWith("Content-length")) { content_length = header_lines.at(i).split(":").at(1).trimmed().toLongLong(); } if(header_lines.at(i).startsWith("Set-Cookie:") && header_lines.at(i).indexOf("=deleted") == -1) { cookie_lines<<header_lines.at(i); } } q_debug()<<"Got Content-length:"<<content_length<<"\n"<<header <<cookie_lines; if(cookie_lines.count() == 0) { q_debug()<<"No login ok cookie found"; return LOGIN_ERROR; } int has_uchome_auth = 0; int has_uchome_loginuser = 0; for(int i = 0 ; i < cookie_lines.count(); i ++) { if(cookie_lines.at(i).indexOf("uchome_auth=") != -1) { has_uchome_auth = 1; } if(cookie_lines.at(i).indexOf("uchome_loginuser="******"may be login faild"; return LOGIN_ERROR; } this->combine_cookies(cookie_lines); return LOGIN_OK; //no use code if(content_length == -1) { q_debug()<<"No content-length field"; //return -1; } QString html ; while(true) { if(!sock->waitForReadyRead()) { q_debug()<<"wait read error"; return -1; } oklen = sock->bytesAvailable(); if(oklen > 0) { html += sock->readAll(); }else{ break; } } q_debug()<<"Got conent size:"<<html.length() <<"\n"<<html; return 0; }
void HttpServerThread::run() { m_server = new BlockingHttpServer(m_features & Ssl); m_server->listen(); m_port = m_server->serverPort(); 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 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; } //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"; } }
int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); for(int i = 0 ; i < argc; i++){ qDebug() << argv[i] << endl; } if(argc >= 4) { //Getting first argument for application QString arg = argv[1]; //Sending mode if(arg == "send") { QTcpSocket *tcpSocket = new QTcpSocket(&a); QString port = argv[3]; tcpSocket->connectToHost(QHostAddress(argv[2]), port.toInt()); if(!tcpSocket->waitForConnected(10*1000)){ qDebug() << "Connection cant be established to host: " << argv[2] << ", at port: " << port << endl; }else{ //Sending mode = file QString type(argv[4]); if(type == "file") { QFile file(argv[5]); if(!file.open(QFile::ReadOnly)) { qDebug() << "Cannot open file" << endl; }else { qDebug() << "File size in bytes: " << file.size() << endl; int counter = 0; //Divide file into chunks of 300KB int chunkSize = 3 * 100000; while(counter < file.size()){ if(!file.seek(counter)){ qDebug() << "Cant seek the file to : " << counter << endl; }else{ QByteArray buffer = file.read(chunkSize); if(!buffer.isEmpty()){ int bytesWritten = tcpSocket->write(buffer); counter += bytesWritten; if(!tcpSocket->waitForBytesWritten(10*1000)) { qDebug() << "Error no bytes written" << tcpSocket->errorString() << endl; }else { qDebug() << "Bytes for writting: " << buffer.size() << ", " << bytesWritten << " bytes written. " << endl; } }else{ qDebug() << "0 bytes read from file, error: " << file.errorString() << endl; break; } } } } //Sending mode = string }else if(type == "string") { QByteArray data = argv[5]; int bytesWritten = tcpSocket->write(data); if(!tcpSocket->waitForBytesWritten(10000)) { qDebug() << "Error no bytes written" << tcpSocket->errorString() << endl; }else { qDebug() << bytesWritten << " bytes written. " << endl; } }else{ qDebug() << "Unknown sending format " << endl; } } tcpSocket->close(); delete tcpSocket; //Receiving mode }else if(arg == "receive") { QTcpServer *tcpServer = new QTcpServer(&a); QString port = argv[3]; if(!tcpServer->listen(QHostAddress(QString(argv[2])),port.toInt())){ qDebug() << "Error, could not start listening, " << tcpServer->serverError() << endl; }else{ QString fileName; QString destinationPath; //Getting name and path for the new file from user bool tryAgain = true; while(tryAgain){ qDebug() << "Enter filename for the new file (ex: picture.png) :"; QTextStream s(stdin); fileName = s.readLine(); qDebug() << "Enter destination path: "; QTextStream d(stdin); destinationPath = d.readLine(); if (!fileName.isEmpty() && !destinationPath.isEmpty()) { qDebug() << "The destination string: " << destinationPath + fileName; tryAgain = false; }else{ qDebug() << "You didnt enter filename, try again" << endl; } } bool working = true; while(working){ if(tcpServer->waitForNewConnection(10*1000)){ QTcpSocket *sock = tcpServer->nextPendingConnection(); sock->waitForReadyRead(10*1000); QByteArray receivedData; QFile file_handle(destinationPath + fileName); //While there is bytes available for receiving, receive them and write chunks of min 300KB to file while(sock->bytesAvailable()){ qDebug() << sock->bytesAvailable() << " bytes available for writting" << endl; receivedData.append(sock->readAll()); if(receivedData.size() > 3 * 100000){ if(!file_handle.isOpen()){ if(!file_handle.open(QFile::WriteOnly | QFile::Append | QFile::Text)){ qDebug() << "Could not open file for writing!" << endl; }else{ file_handle.write(receivedData); file_handle.flush(); file_handle.waitForBytesWritten(10*1000); qDebug() << "Written " << receivedData.size() << " to file. In KB = " << receivedData.size() / 1000 << endl; receivedData.clear(); } }else{ file_handle.write(receivedData); file_handle.flush(); file_handle.waitForBytesWritten(10*1000); qDebug() << "Written " << receivedData.size() << " to file. In KB = " << receivedData.size() / 1000 << endl; receivedData.clear(); } } sock->waitForReadyRead(10*1000); } file_handle.close(); //In case there is still data in buffer, but data is smaller than 300KB than append that remaining data to file also if(receivedData.size() != 0){ qDebug() << "Preparing to write remaining chunks of data" << endl; if(!file_handle.open(QFile::WriteOnly)){ qDebug() << "Could not open file for writing!" << endl; }else{ file_handle.write(receivedData); file_handle.flush(); file_handle.waitForBytesWritten(10*1000); qDebug() << "Written " << receivedData.size() << " to file. In MB = " << receivedData.size() / 1000000 << endl; receivedData.clear(); file_handle.close(); } } sock->close(); delete sock; // file_thread->deleteLater(); qDebug() << "Should i wait for other request? (y/n) default = yes" ; char answer; cin >> answer; if(answer == 'n'){ working = false; tcpServer->close(); delete tcpServer; } }else{ qDebug() << "No incoming connection" << endl; qDebug() << "Should i check for another request? (Yes / No)" ; char answer; cin >> answer; if(answer == 'n'){ working = false; tcpServer->close(); delete tcpServer; } } }
void CClient::readyRead() { QTcpSocket *socket = m_socket; QByteArray data = socket->readAll(); //-- QINT64 QByteArray code = data.left(500); //-- On prend un échantillon pour voir le code QString ligne = QString(code); if (ligne.length() > 0) { //-- On analyse ce qu'on a reçu à savoir si c'est un code de commande if (ligne.at(0) == COMMAND_CODE) { QStringList lst = ligne.split('|'); if (lst[0] == "%SURNOM") { ligne = QString(data); lst = ligne.split('|'); m_Surnom = lst[1]; emit signalUserName(GetNomClient()); //-- On répond pour dire que nous avons reçu la commande QByteArray bOK; bOK.append(QString("%OK")); socket->write(bOK); socket->waitForBytesWritten(); sleep(1); emit demandeEnvoiListeClients(); } if (lst[0] == "%MESSAGE") { ligne = QString(data); lst = ligne.split('|'); emit transmetMessage(lst[1], lst[2], lst[3]); } if (lst[0] == "%FICHIER") { //-- %1 - Source //-- %2 - Destinataire //-- %3 - Nb bytes ecrit //-- %4 - Nb bytes total //-- %5 - Nom fichier //-- %6 - Data //QMessageBox::information(0, "", QString("%1|%2|%3|%4|%5").arg(lst[1], lst[2], lst[3], lst[4], lst[5])); int posDepartImage = 7 + lst[1].length() + lst[2].length() + lst[3].length() + lst[4].length() + lst[5].length(); emit transmetFichier(lst[1], lst[2], lst[3], lst[4], lst[5], data.right(data.count() - posDepartImage)); } if (lst[0] == "%PING") { emit pingRecu(GetNomClient()); } } } }
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 = 2; 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 = 2; 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 = filename; // Encode just avi files for now if(encPath.endsWith(".avi") || encPath.endsWith(".mp4")) { encPath.insert(encPath.lastIndexOf('.'), ".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"; } 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 { QStringList args; args.append(filename); args.append("-ovc"); args.append("lavc"); args.append("-lavcopts"); args.append("vcodec=mpeg4:vhq:vbitrate=300"); args.append("-vf"); args.append("scale=320:240,eq2=1.2:0.5:-0.25,rotate=2"); args.append("-oac"); args.append("mp3lame"); args.append("-ofps"); args.append("15"); args.append("-lameopts"); args.append("br=64:cbr"); args.append("-o"); args.append(encPath); process = new QProcess(this); process->setProcessChannelMode(QProcess::ForwardedChannels); process->start("mencoder", args); #ifdef Q_WS_WIN PROCESS_INFORMATION *pi = (PROCESS_INFORMATION *) process->pid(); SetPriorityClass(pi->hProcess, IDLE_PRIORITY_CLASS); #endif // FIXME: whatever we send to back, browser wont show anything if(process->waitForStarted(10000)) { res.append("Encoding started</br>Reload page to check status or download"); } else { res.append("Failed to start mencoder:</br>"); res.append(process->errorString()); delete(process); process = NULL; } } } } 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(); }
void CClientApp::sendCommandToServer(QVariantMap cmdMap) { QTcpSocket *socket = new QTcpSocket(this); //serverIP = "192.168.0.238"; QString command = cmdMap["command"].toString(); QJsonObject jsonObj; if (command == "listDevices") { jsonObj.insert("command", command); } else if (command == "listCommands") { QString deviceUID = cmdMap["uid"].toString(); jsonObj.insert("command", command); jsonObj.insert("uid", deviceUID); } else if (command == "sendCommandToDevice") { QString deviceUID = cmdMap["uid"].toString(); QString deviceCmd = cmdMap["deviceCmd"].toString(); QString deviceParam = cmdMap["param"].toString(); jsonObj.insert("command", command); jsonObj.insert("uid", deviceUID); jsonObj.insert("deviceCmd", deviceCmd); jsonObj.insert("param", deviceParam); } QJsonDocument doc(jsonObj); Q_EMIT m_pSender->commandReturned("SendCmdToServer: " + QString::fromLatin1(doc.toJson()) + "\n", false); QObject::connect(socket, &QTcpSocket::readyRead, [=] { QByteArray byteArray = socket->readAll(); QJsonDocument jsonDoc = QJsonDocument::fromJson(byteArray); QJsonObject jsonObj = jsonDoc.object(); QString kText("Cmd Return Result: " + QString::number(jsonObj["status"].toInt()) + "\n"); if (jsonObj["status"].toInt() == 200) { QVariantMap retMap = jsonObj.toVariantMap(); qDebug() << jsonObj["devices"].toArray().size(); parseDataToQML(retMap); kText += QString::fromLatin1(byteArray) + "\n"; } Q_EMIT m_pSender->commandReturned(kText, false); socket->disconnectFromHost(); }); QObject::connect(socket, &QTcpSocket::disconnected, [=] { socket->deleteLater(); }); socket->connectToHost(serverIP, 3479, QIODevice::ReadWrite); socket->write(doc.toJson()); bool bSentCmd = socket->waitForBytesWritten(); QString result = (bSentCmd ? "true" : "false"); Q_EMIT m_pSender->commandReturned("Cmd Sent: " + result, false); }
void CClientApp::processDeviceCommandSocket() { QTcpSocket *socket = deviceCmdServer->nextPendingConnection(); QString kText("Recieve TCP Socket\n"); Q_EMIT m_pSender->commandReturned(kText, false); QObject::connect(socket, &QTcpSocket::readyRead, [=] { QByteArray byteArray = socket->readAll(); QJsonDocument jsonDoc = QJsonDocument::fromJson(byteArray); QJsonObject jsonObj = jsonDoc.object(); QString command = jsonObj["command"].toString(); QString retJsonString; QJsonObject retJsonObj; QString kText("Recieve Cmd: " + command + "\n"); if (command == "supportCmds") { retJsonObj.insert("status", 200); QJsonArray cmdArray; /* QJsonObject cmdObj1; cmdObj1.insert("command", "adjustTemperature"); cmdObj1.insert("command_displayName", "Set Temperature"); cmdObj1.insert("param_type", "integer"); cmdObj1.insert("param_max", "100"); cmdObj1.insert("param_min", "20"); QJsonObject cmdObj2; cmdObj2.insert("command", "query"); cmdObj2.insert("command_displayName", "Query Status"); cmdObj2.insert("param_type", "none"); cmdArray.append(cmdObj1); cmdArray.append(cmdObj2); */ retJsonObj.insert("SupportCmds", cmdArray); connected = true; } else if (command == "queryDisplayInfo") { retJsonObj.insert("status", 200); QJsonArray keyArray; keyArray.append("Power"); //keyArray.append("WindStrength"); //keyArray.append("Humidity"); retJsonObj.insert("DisplayInfo", keyArray); //retJsonObj.insert("Temperature", QString::number(temperature)); //retJsonObj.insert("WindStrength", "Medium"); //retJsonObj.insert("Humidity", "60"); retJsonObj.insert("Power", "On"); } /*else if (command == "adjustTemperature") { temperature = jsonObj["param"].toString().toInt(); retJsonObj.insert("status", 200); }*/ else { kText += command + " " + jsonObj["param"].toVariant().toString() + "\n"; retJsonObj.insert("status", 200); } QJsonDocument retDoc(retJsonObj); kText += "WritingServer: " + QString::fromLatin1(retDoc.toJson()) + "\n"; socket->write(retDoc.toJson()); bool isSuccess = socket->waitForBytesWritten(); QString result = (isSuccess ? "true" : "false"); kText += "Written: " + result + "\n"; socket->disconnectFromHost(); Q_EMIT m_pSender->commandReturned(kText, false); }); QObject::connect(socket, &QTcpSocket::disconnected, [=] { socket->deleteLater(); }); }
//SLOT to readyRead. Called upon data arrival void MiniServer::readyRead() { QTcpSocket *socket = (QTcpSocket *)sender(); //Get the socket that sent data int p = 0, len = socDataList.size(); socketData *socDes = NULL; for ( ; p < len; p++) { //Get socDes according to that socket if (socDataList.at(p)->socketDesciptor == socket->socketDescriptor()) { socDes = socDataList.at(p); break; } } QByteArray Data = socket->readAll(); //Read data from the buffer that comes on the socket int i = 0; //Process the message which will start with start byte and then data for (i = 0; i < Data.size(); i++) { //If dataRead is on then read data into buffer till buffer's size is matched to expected size if (!socDes->readingStart && socDes->dataRead && socDes->buffer.size() < (socDes->end-(qint64)(socDes->start.toLong())+1)) { socDes->buffer.append(Data[i]); continue; } //If expected data is in buffer then .... if ((socDes->buffer.size() == (socDes->end - (qint64)(socDes->start.toLong()) + 1)) && socDes->dataRead) { //qDebug() << "got"; fstream file; file.open(this->filename.toUtf8().constData(), ios::in | ios::out | ios::ate); if (!map[(qint64)(socDes->start.toLong())]) { //If data is already not written QCryptographicHash *ha = new QCryptographicHash(QCryptographicHash::Md5); ha->addData(socDes->buffer.constData()); QString hash = QString(ha->result().toHex()); if (!hash.compare(this->pieceHashes.at(((qint64)socDes->start.toLong())/this->pieceSize))) { //Check hash of the piece //Mark it as data written and write data and emit signal that data is written map[(qint64)(socDes->start.toLong())] = true; file.seekp(socDes->start.toLong(), ios::beg); file.write(socDes->buffer.constData(), socDes->buffer.size()); this->numberOfBytesWritten += socDes->buffer.size(); //Update number of bytes written emit dataGot(); if (this->numberOfBytesWritten == this->size) { file.close(); //Check if file transfer is done emit fileTransferDone(); } } else { //If piece is dirty then ask the request the next client to send data. qint64 end = this->size-1 < ((qint64)socDes->start.toLong() + this->pieceSize - 1) ? this->size-1 : ((qint64)socDes->start.toLong() + this->pieceSize - 1); QString request = " R " + QString::number((qint64)socDes->start.toLong()) + " " + QString::number(end) + " "; int i = 0; for ( ; i < clientList.size(); i++) { if (clientList.at(i)->socketDescriptor() == socket->socketDescriptor()) break; } i = (i + 1) % clientList.size(); clientList.at(i)->write(request.toUtf8()); clientList.at(i)->waitForBytesWritten(); file.close(); continue; } } //Issue next request till sizechk is less than size if(this->sizechk < this->size) { qint64 end = this->size-1 < (this->sizechk + this->pieceSize - 1) ? this->size-1 : (this->sizechk + this->pieceSize - 1); QString request = " R " + QString::number(this->sizechk) + " " + QString::number(end) + " "; this->sizechk = end + 1; socket->write(request.toUtf8()); socket->waitForBytesWritten(); } else { //Else check if there is some data missing and request that data qint64 start = 0; while (start < this->size) { if (!map[start]) { qint64 end = this->size-1 < (start + this->pieceSize - 1) ? (this->size - 1) : (start + this->pieceSize - 1); QString request = " R " + QString::number(start) + " " + QString::number(end) + " "; socket->write(request.toUtf8()); socket->waitForBytesWritten(); break; } start += this->pieceSize; } } file.close(); socDes->buffer.clear(); socDes->dataRead = false; continue; } if (!socDes->readingStart) { //Start reading start byte socDes->start.clear(); socDes->readingStart = true; socDes->dataRead = false; continue; } if (socDes->readingStart) { //start reading start till ' ' comes if (char(Data[i]) != ' ') { socDes->start.append(Data[i]); continue; } else { socDes->readingStart = false; //Decide end byte and make dataRead true socDes->end = (this->size - 1) < ((qint64)(socDes->start.toLong()) + this->pieceSize - 1) ? (this->size - 1) : (qint64)(socDes->start.toLong()) + this->pieceSize - 1; socDes->dataRead = true; continue; } } } }