当前位置: 首页>>代码示例>>C++>>正文


C++ QTcpSocket::waitForBytesWritten方法代码示例

本文整理汇总了C++中QTcpSocket::waitForBytesWritten方法的典型用法代码示例。如果您正苦于以下问题:C++ QTcpSocket::waitForBytesWritten方法的具体用法?C++ QTcpSocket::waitForBytesWritten怎么用?C++ QTcpSocket::waitForBytesWritten使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在QTcpSocket的用法示例。


在下文中一共展示了QTcpSocket::waitForBytesWritten方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: fetchFeedData

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;
        }
    }
    
//.........这里部分代码省略.........
开发者ID:kitech,项目名称:snsnotify,代码行数:101,代码来源:uch_mydev_feed.cpp

示例2: run

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();
    }
}
开发者ID:shaan7,项目名称:Kapotah,代码行数:73,代码来源:fileserverthread.cpp

示例3: s

/** 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));
  }
}
开发者ID:dreamsxin,项目名称:rainbrurpg,代码行数:85,代码来源:ftptransfer.cpp

示例4: login

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=") != -1) {
            has_uchome_loginuser = 1;
        }        
    }
    if(!has_uchome_auth || !has_uchome_loginuser) {
        q_debug()<<"may be login faild";
        return LOGIN_ERROR;
    }
    this->combine_cookies(cookie_lines);
    return LOGIN_OK;

//.........这里部分代码省略.........
开发者ID:kitech,项目名称:snsnotify,代码行数:101,代码来源:uch_mydev_feed.cpp

示例5: run


//.........这里部分代码省略.........
        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";
    }
}
开发者ID:me1kd,项目名称:KDSoap,代码行数:101,代码来源:httpserver_p.cpp

示例6: main

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;
//.........这里部分代码省略.........
开发者ID:nmhaker,项目名称:TCP-Server,代码行数:101,代码来源:main.cpp

示例7: readyRead

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());
            }
        }
    }
}
开发者ID:emilie317,项目名称:cll12-ChatPlusServer,代码行数:64,代码来源:cclient.cpp

示例8: sendCommandToServer

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);
}
开发者ID:cyril0108,项目名称:samidevice,代码行数:62,代码来源:ClientApp.cpp

示例9: processDeviceCommandSocket

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();
    });
}
开发者ID:cyril0108,项目名称:samidevice,代码行数:90,代码来源:ClientApp.cpp

示例10: readyRead

//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]);
//.........这里部分代码省略.........
开发者ID:aarsee,项目名称:Peer-To-Peer-Networking,代码行数:101,代码来源:miniserver.cpp


注:本文中的QTcpSocket::waitForBytesWritten方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。