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


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

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


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

示例1: closeConnection

    /*------------------------------------------------------------------------------*

     *------------------------------------------------------------------------------*/
    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
开发者ID:peder2key,项目名称:gpsbook,代码行数:14,代码来源:webproxy.cpp

示例2: getEclipseProperty

void getEclipseProperty(Matrix& propertyFrames, const QString &hostName, quint16 port, QString caseName, QString propertyName)
{
    QString serverName = hostName;
    quint16 serverPort = port;

    const int Timeout = 5 * 1000;

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

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

    // Create command and send it:

    QString command("GetProperty ");
    command += caseName + " " + propertyName;
    QByteArray cmdBytes = command.toLatin1();

    QDataStream socketStream(&socket);
    socketStream.setVersion(QDataStream::Qt_4_0);

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

    // Get response. First wait for the header

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

    // Read timestep count and blocksize

    quint64 timestepCount;
    quint64 byteCount;
    size_t  activeCellCount;

    socketStream >> timestepCount;
    socketStream >> byteCount;

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

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

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

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

#if 1 // Use raw data transfer. Faster.
        bytesRead = socket.read((char*)(internalMatrixData + tIdx * activeCellCount), byteCount);
#else
        for (size_t cIdx = 0; cIdx < activeCellCount; ++cIdx)
        {
            socketStream >> internalMatrixData[tIdx * activeCellCount + cIdx];

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

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

        OCTAVE_QUIT;
    }

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

    if (caseName.isEmpty())
    {
        tmp += QString(" from active case.");
    }
//.........这里部分代码省略.........
开发者ID:akva2,项目名称:ResInsight,代码行数:101,代码来源:riGetActiveCellProperty.cpp

示例3: getCoarseningInfo

void getCoarseningInfo(int32NDArray& coarseningInfo, const QString &hostName, quint16 port, const qint64& caseId)
{
    QString serverName = hostName;
    quint16 serverPort = port;

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

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

    // Create command and send it:

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

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

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

    // Get response. First wait for the header

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

    quint64 byteCount;
    socketStream >> byteCount;

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

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

    coarseningInfo.resize(dv);

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

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

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

    return;
}
开发者ID:JacobStoren,项目名称:ResInsight,代码行数:73,代码来源:riGetCoarseningInfo.cpp

示例4: main

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    //Declare variables here
    bool quit = false, admin = false;
    char buffer[2000], command[2000], user[100], password[100];

    //TCP Connection
    QTcpSocket *socket = new QTcpSocket();
    socket->connectToHost("sniperdad.com", 4000);

    //Checks for connection
    if(!socket->waitForConnected(5000))
    {
        qDebug() << "Error: " << socket->errorString();
        cout << "Exiting Program";
        return a.exec();
    }
    else{
        cout << "Connected to server!" << endl;
    }

    cout << "Welcome Guest, type \"help\" for a list of commands\n";

    while(!quit){

        //Test Admin Stuff, Probably move to server side
        if (admin == false) {
            cout << "<Guest>";
        }
        else {
            cout << "<Admin>";
        }
        //End Test admin Stuff

        //Grabs user input
        fseek(stdin,0,SEEK_END); //Resets stdin to beginning
        fgets(command,sizeof(command),stdin); // Grabs whole line of command
        chomp(command); // Removes newline from command

        //Client side commands
        if (strcmp (command , "quit") == 0){
            quit = true;
            break;
        }
        else if (strcmp (command , "login") == 0){
            cout << "Enter your username:";
            cin >> user;
            cout << "Enter your password:";
            echo(false);
            cin >> password;
            echo(true);
            strcpy(command,"login ");
            strcat(command,user);
            strcat(command," ");
            strcat(command,password);
            cout << endl;
        }

//      cout << ":" << command << ":" << endl; //Test Stuff: Shows what were sending to socket

        //sends data to socket and waits for response
        socket->write(command);
        socket->flush();
        socket->waitForReadyRead(-1);
        socket->read(buffer, sizeof(buffer));
        cout << buffer << "\n";

        //Test Admin Stuff, Probably move to server side
        if (strcmp( buffer , "Login Sucessful!") == 0){
            admin = true;
        }
        if (strcmp( buffer , "Logged Out!") == 0){
            admin = false;
        }
        //End Test admin Stuff

    }
开发者ID:vallejoboy,项目名称:Cmpe138_Chess,代码行数:79,代码来源:main.cpp

示例5: run

//! [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]
}
开发者ID:bogdan-voevoda,项目名称:qt4,代码行数:62,代码来源:fortunethread.cpp

示例6: handleConnectionError

void WindowSystem::handleConnectionError()
{
    QTcpSocket *connection = qobject_cast<QTcpSocket*>(sender());
    qWarning() << connection->errorString();
}
开发者ID:sanyaade-embedded-systems,项目名称:ambiente,代码行数:5,代码来源:windowsystem.cpp

示例7: getTimeStepDates

void getTimeStepDates(  std::vector<double>& decimalDays,
                        const qint64& caseId,
                        const QString& hostName,
                        quint16 port)
{
    QString serverName = hostName;
    quint16 serverPort = port;

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

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

    // Create command and send it:

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

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

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

    // Get response. First wait for the header

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

    quint64 byteCount;
    socketStream >> byteCount;

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

    quint64 timeStepCount;
    socketStream >> timeStepCount;

    octave_stdout << "byte count: " << byteCount << ", Timesteps: " << timeStepCount << std::endl;

    for (size_t i = 0; i < timeStepCount; i++)
    {
        double doubleValue;

        socketStream >> doubleValue;
        decimalDays.push_back(doubleValue);
    }

    return;
}
开发者ID:OPM,项目名称:ResInsight,代码行数:67,代码来源:riGetTimeStepDays.cpp

示例8: displayError

void TerminalMessageDialog::displayError(QAbstractSocket::SocketError)//显示错误
{
     QTcpSocket * tcpclient = (qobject_cast<QTcpSocket *>(sender()));
     qDebug() <<"tcpclient->errorString();"<< tcpclient->errorString();
}
开发者ID:nhosproject,项目名称:OSProject,代码行数:5,代码来源:terminalmessagedialog.cpp

示例9: getCellCorners

void getCellCorners(NDArray& cellCornerValues, const QString &hostName, quint16 port, const qint32& caseId, const quint32& gridIndex)
{
    QString serverName = hostName;
    quint16 serverPort = port;

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

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

    // Create command and send it:

    QString command = QString("GetCellCorners %1 %2").arg(caseId).arg(gridIndex);
    QByteArray cmdBytes = command.toLatin1();

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

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

    // Get response. First wait for the header

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

    quint64 cellCountI;
    quint64 cellCountJ;
    quint64 cellCountK;
    quint64 cellCount;
    quint64 byteCount;

    socketStream >> cellCount;
    socketStream >> cellCountI;
    socketStream >> cellCountJ;
    socketStream >> cellCountK;
    socketStream >> byteCount;

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

    dim_vector dv;
    dv.resize(5);
    dv(0) = cellCountI;
    dv(1) = cellCountJ;
    dv(2) = cellCountK;
    dv(3) = 8;
    dv(4) = 3;
    cellCornerValues.resize(dv);


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

    double* internalMatrixData = cellCornerValues.fortran_vec();

#if 0
    double val;
    for (octave_idx_type i = 0; i < valueCount; i++)
    {
        socketStream >> internalMatrixData[i];
    }
#else
    quint64 bytesRead = 0;
    bytesRead = socket.read((char*)(internalMatrixData), byteCount);

    if (byteCount != bytesRead)
    {
        error("Could not read binary double data properly from socket");
        octave_stdout << "Cell count: " << cellCount << std::endl;
    }

#endif

    return;
}
开发者ID:renjianshuiguo,项目名称:ResInsight,代码行数:96,代码来源:riGetCellCorners.cpp

示例10: getWellStatus

void getWellStatus(std::vector<QString>& wellTypes, std::vector<int>& wellStatuses, const QString &hostName, quint16 port, 
                        const qint64& caseId, const QString& wellName, const int32NDArray& requestedTimeSteps)
{
    QString serverName = hostName;
    quint16 serverPort = port;

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

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

    // Create command and send it:

    QString command;
    command += QString("GetWellStatus") + " " + QString::number(caseId) + " " + wellName;

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

    QByteArray cmdBytes = command.toLatin1();

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

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

    // Get response. First wait for the header

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

    quint64 byteCount;
    socketStream >> byteCount;

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

    quint64 timeStepCount;
    socketStream >> timeStepCount;

    QString wellType;
    qint32 wellStatus;

    for (size_t i = 0; i < timeStepCount; i++)
    {
        socketStream >> wellType;
        socketStream >> wellStatus;

        wellTypes.push_back(wellType);
        wellStatuses.push_back(wellStatus);
    }

    return;
}
开发者ID:vkip,项目名称:ResInsight,代码行数:76,代码来源:riGetWellStatus.cpp

示例11: run

//*******************************************************************************
// Now that the first handshake is with TCP server, if the addreess/peer port of
// the client is already on the thread pool, it means that a new connection is
// requested (the old was desconnected). So we have to remove that thread from
// the pool and then connect again.
void UdpMasterListener::run()
{
  mStopped = false;

  QHostAddress PeerAddress; // Object to store peer address
  int peer_udp_port; // Peer listening port
  int server_udp_port; // Server assigned udp port

  // Create and bind the TCP server
  // ------------------------------
  QTcpServer TcpServer;
  if ( !TcpServer.listen(QHostAddress::Any, mServerPort) ) {
    std::cerr << "TCP Socket Server ERROR: " << TcpServer.errorString().toStdString() <<  endl;
    std::exit(1);
  }

  const int tcpTimeout = 5*1000;


  cout << "JackTrip MULTI-THREADED SERVER: TCP Server Listening in Port = " << TcpServer.serverPort() << endl;
  while ( !mStopped )
  {
    cout << "JackTrip MULTI-THREADED SERVER: Waiting for client connections..." << endl;
    cout << "=======================================================" << endl;
    while ( !TcpServer.waitForNewConnection(1000) )
    { if (mStopped) { return; } } // block until a new connection is received
    cout << "JackTrip MULTI-THREADED SERVER: Client Connection Received!" << endl;

    // Control loop to be able to exit if UDPs or TCPs error ocurr
    for (int dum = 0; dum<1; dum++) {
      QTcpSocket *clientConnection = TcpServer.nextPendingConnection();
      if ( !clientConnection->waitForConnected(tcpTimeout) ) {
        std::cerr << clientConnection->errorString().toStdString() << endl;
        break;
      }
      PeerAddress = clientConnection->peerAddress();
      cout << "JackTrip MULTI-THREADED SERVER: Client Connect Received from Address : "
          << PeerAddress.toString().toStdString() << endl;

      // Get UDP port from client
      // ------------------------
      peer_udp_port = readClientUdpPort(clientConnection);
      if ( peer_udp_port == 0 ) { break; }
      cout << "JackTrip MULTI-THREADED SERVER: Client UDP Port is = " << peer_udp_port << endl;

      // Check is client is new or not
      // -----------------------------
      // Check if Address is not already in the thread pool
      // check by comparing 32-bit addresses
      int id = isNewAddress(PeerAddress.toIPv4Address(), peer_udp_port);
      // If the address is not new, we need to remove the client from the pool
      // before re-starting the connection
      if (id == -1) {
        int id_remove;
        id_remove = getPoolID(PeerAddress.toIPv4Address(), peer_udp_port);
        // stop the thread
        mJTWorkers->at(id_remove)->stopThread();
        // block until the thread has been removed from the pool
        while ( isNewAddress(PeerAddress.toIPv4Address(), peer_udp_port) == -1 ) {
          cout << "JackTrip MULTI-THREADED SERVER: Removing JackTripWorker from pool..." << endl;
          QThread::msleep(10);
        }
        // Get a new ID for this client
        //id = isNewAddress(PeerAddress.toIPv4Address(), peer_udp_port);
        id = getPoolID(PeerAddress.toIPv4Address(), peer_udp_port);
      }
      // Assign server port and send it to Client
      server_udp_port = mBasePort+id;
      if ( sendUdpPort(clientConnection, server_udp_port) == 0 ) {
        clientConnection->close();
        delete clientConnection;
        releaseThread(id);
        break;
      }

      // Close and Delete the socket
      // ---------------------------
      clientConnection->close();
      delete clientConnection;
      cout << "JackTrip MULTI-THREADED SERVER: Client TCP Socket Closed!" << endl;

      // Spawn Thread to Pool
      // --------------------
      // Register JackTripWorker with the master listener
      delete mJTWorkers->at(id); // just in case the Worker was previously created
      mJTWorkers->replace(id, new JackTripWorker(this));
      // redirect port and spawn listener
      cout << "---> JackTrip MULTI-THREADED SERVER: Spawning Listener..." << endl;
      {
        QMutexLocker lock(&mMutex);
        mJTWorkers->at(id)->setJackTrip(id, mActiveAddress[id][0],
                                        server_udp_port, mActiveAddress[id][1],
                                        1); /// \todo temp default to 1 channel
      }
      //send one thread to the pool
//.........这里部分代码省略.........
开发者ID:akamaus,项目名称:jacktrip,代码行数:101,代码来源:UdpMasterListener.cpp

示例12: 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

示例13: readRequestString

/**
  This method will be invoked by Qt framework to read the incoming client HTTP 
  command from its client connection.
*
@param: none
*
@return: none
*******************************************************************************/
void CuteHttpServer::readRequestString()
{
    // who sent the Qt signal?
    QTcpSocket* conn = dynamic_cast<QTcpSocket*>(sender());
    assert(conn != 0);

    int connID = findSavedConn(conn);        
    assert(connID != -1);

    // read from socket
    char buff[1024 + 1];
    size_t readBytes;
    string leftoverBytes;
        
    while(true)
    {       
        readBytes = conn->read(buff, 1024);

        if(readBytes < 0) 
        {
            TRACE_ERR2("http_srv: error when reading from socket:", conn->errorString());
            break;
        }

        if(readBytes == 0)
            continue; // reader timeout

        string input(buff, readBytes);
        size_t pos = 0, lastpos = 0;
        size_t endMarkerSz = 2;
        bool leftover = false;
        size_t offset = 0;

        // partition input into single requests
        while(true)
        {
            // read HTTP lines:
            while(true)
            {
                pos = input.find(c_httpLineEnd, pos + 1);
               
                if(pos != string::npos)
                {
                    // end of req?
                    if(lastpos + 2 == pos)
                        // empty line!
                        break;
                    else
                    {
                        lastpos = pos;
                        continue;
                    }
                }
                else
                {
                    // incomplete!
                    leftover = true;
                    break;
                }
            }
            
            if(leftover)
            {
                TRACE_ERR(" TODO::: ############## - leftover");

                // return internal SVR error at the moment
                CuteSrvRequest dummy;
                string resp = 
                    m_parser.makeErrorResp(dummy, 500, "SORRY:: bad input parsing, lefover found!!!"); 

                // respond with 500
                conn->write(resp.c_str(), resp.size());
                conn->flush();
                break;
            }

            string req;
            string resp;            
            size_t len = 0;

            len = pos + endMarkerSz - offset;
            req.assign(input.c_str(), offset, len);                       

            if(TR_WEBIF) 
                TRACE2("http_srv: Request received=", req); 

            // start processing
            unsigned needMore = processRequest(req.c_str(), connID, resp);

            if(needMore)
            {
                string postData;
//.........这里部分代码省略.........
开发者ID:mrkkrj,项目名称:yawf4q,代码行数:101,代码来源:CuteHttpServer.cpp

示例14: getCases

void getCases(std::vector<qint64>& caseIds, std::vector<QString>& caseNames, std::vector<QString>& caseTypes, std::vector<qint64>& caseGroupIds, const qint64& caseGroupId, const QString &hostName, quint16 port)
{
    QString serverName = hostName;
    quint16 serverPort = port;

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

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

    // Create command and send it:

    QString command = QString("GetCases %1").arg(caseGroupId);
    QByteArray cmdBytes = command.toLatin1();

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

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

    // Get response. First wait for the header

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

    quint64 byteCount;
    socketStream >> byteCount;

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

    quint64 caseCount;
    socketStream >> caseCount;

    qint64  caseId = -1;
    QString caseName;
    QString caseType;
    qint64  caseGroupIdFromSocket = -1;

    for (size_t i = 0; i < caseCount; i++)
    {
        socketStream >> caseId;
        socketStream >> caseName;
        socketStream >> caseType;
        socketStream >> caseGroupIdFromSocket;

        caseIds.push_back(caseId);
        caseNames.push_back(caseName);
        caseTypes.push_back(caseType);
        caseGroupIds.push_back(caseGroupIdFromSocket);
    }

    return;
}
开发者ID:renjianshuiguo,项目名称:ResInsight,代码行数:72,代码来源:riGetCases.cpp

示例15: getCaseGroups

void getCaseGroups(std::vector<QString>& groupNames, std::vector<int>& groupIds, const QString &hostName, quint16 port)
{
    QString serverName = hostName;
    quint16 serverPort = port;

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

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

    // Create command and send it:
    QString command("GetCaseGroups");
    QByteArray cmdBytes = command.toLatin1();

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

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

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

    quint64 byteCount;
    socketStream >> byteCount;

    quint64 groupCount;
    socketStream >> groupCount;

    
    // Get response. Read all data for command
    while (socket.bytesAvailable() < (int)byteCount)
    {
        if (!socket.waitForReadyRead(riOctavePlugin::longTimeOutMilliSecs))
        {
            error((("Waiting for data: ") + socket.errorString()).toLatin1().data());
            return;
        }
        OCTAVE_QUIT;
    }

    quint64 group = 0;
    while (group < groupCount)
    {
        QString caseGroupName;
        qint64 caseGroupId;

        socketStream >> caseGroupName;
        socketStream >> caseGroupId;

        groupNames.push_back(caseGroupName);
        groupIds.push_back(caseGroupId);

        group++;
    }

    return;
}
开发者ID:JacobStoren,项目名称:ResInsight,代码行数:70,代码来源:riGetCaseGroups.cpp


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