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;
}
Exemple #2
0
    /*------------------------------------------------------------------------------*

     *------------------------------------------------------------------------------*/
    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
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.");
    }
    else
    {
        tmp += QString(" from %1.").arg(caseName);
    }
    octave_stdout << tmp.toStdString() << " Active cells : " << activeCellCount << ", Timesteps : " << timestepCount << std::endl;

    return;
}
void getActiveCellProperty(Matrix& propertyFrames, const QString &serverName, quint16 serverPort,
                        const qint64& caseId, QString propertyName, const int32NDArray& requestedTimeSteps, QString porosityModel)
{
    QTcpSocket socket;
    socket.connectToHost(serverName, serverPort);

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

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

    // Create command as a string with arguments , and send it:

    QString command;
    command += "GetActiveCellProperty " + QString::number(caseId) + " " + propertyName + " " + porosityModel;

    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();

    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 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(riOctavePlugin::longTimeOutMilliSecs))
            {
                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 0
        // Raw data transfer. Faster. Not possible when dealing with coarsening
        // bytesRead = socket.read((char*)(internalMatrixData + tIdx * activeCellCount), byteCount);
#else
        // Compatible transfer. Now the only one working
        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 (caseId < 0)
    {
        tmp += QString(" from current case.");
    }
    else
    {
        tmp += QString(" from case with Id: %1.").arg(caseId);
    }
    octave_stdout << tmp.toStdString() << " Active cells : " << activeCellCount << ", Timesteps : " << timestepCount << std::endl;

    return;
}
Exemple #5
0
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:"******"Enter your password:"******"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

    }
void setEclipseProperty(const Matrix& propertyFrames, const QString &hostName, quint16 port,
                        const qint64& caseId, QString propertyName, const int32NDArray& requestedTimeSteps, QString porosityModel)
{
    QTcpSocket socket;
    socket.connectToHost(hostName, port);

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

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

    // Create command as a string with arguments , and send it:

    QString command;
    command += "SetActiveCellProperty " + QString::number(caseId) + " " + propertyName + " " + porosityModel;

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

    QByteArray cmdBytes = command.toLatin1();

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

    // Write property data header

    dim_vector mxDims = propertyFrames.dims();

    qint64 cellCount = mxDims.elem(0);
    qint64 timeStepCount = mxDims.elem(1);
    qint64 timeStepByteCount = cellCount * sizeof(double);

    socketStream << (qint64)(timeStepCount);
    socketStream << (qint64)timeStepByteCount;

    const double* internalData = propertyFrames.fortran_vec();

    QStringList errorMessages;
    if (!RiaSocketDataTransfer::writeBlockDataToSocket(&socket, (const char *)internalData, timeStepByteCount*timeStepCount, errorMessages))
    {
        for (int i = 0; i < errorMessages.size(); i++)
        {
            octave_stdout << errorMessages[i].toStdString();
        }

        return;
    }

    QString tmp = QString("riSetActiveCellProperty : Wrote %1").arg(propertyName);

    if (caseId == -1)
    {
        tmp += QString(" to current case.");
    }
    else
    {
        tmp += QString(" to case with Id = %1.").arg(caseId);
    }
    octave_stdout << tmp.toStdString() << " Active Cells : " << cellCount << " Time steps : " << timeStepCount << std::endl;

    while(socket.bytesToWrite() && socket.state() == QAbstractSocket::ConnectedState)
    {
        // octave_stdout << "Bytes to write: " << socket.bytesToWrite() << std::endl;
        socket.waitForBytesWritten(riOctavePlugin::shortTimeOutMilliSecs);
        OCTAVE_QUIT;
    }

    //octave_stdout << "    Socket write completed" << std::endl;

    if (socket.bytesToWrite() && socket.state() != QAbstractSocket::ConnectedState)
    {
        error("riSetActiveCellProperty : ResInsight refused to accept the data. Maybe the dimensions or porosity model is wrong");
    }

#ifdef WIN32
    // TODO: Due to synchronization issues seen on Windows 10, it is required to do a sleep here to be able to catch disconnect
    // signals from the socket. No sleep causes the server to hang.

    Sleep(100);

#endif //WIN32

    return;
}
void getPropertyNames(std::vector<QString>& propNames, std::vector<QString>& propTypes, const QString &hostName, quint16 port, 
                        const qint64& caseId, QString porosityModel)
{
    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("GetPropertyNames") + " " + QString::number(caseId) + " " + porosityModel;
    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;
    QString byteCountString = QString::number(byteCount);

    //error(byteCountString.toLatin1().data());

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

    quint64 propCount;
    socketStream >> propCount;

    QString propName;
    QString propType;

    for (size_t i = 0; i < propCount; i++)
    {
        socketStream >> propName;
        socketStream >> propType;

        propNames.push_back(propName);
        propTypes.push_back(propType);
    }

    return;
}
Exemple #8
0
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;
}
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;
}
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;
}
Exemple #11
0
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;
}
//*******************************************************************************
// 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
      cout << "---> JackTrip MULTI-THREADED SERVER: Starting Thread..." << endl;
      mThreadPool.start(mJTWorkers->at(id), QThread::TimeCriticalPriority);
      // wait until one is complete before another spawns
      while (mJTWorkers->at(id)->isSpawning()) { QThread::msleep(10); }
      //mTotalRunningThreads++;
      cout << "JackTrip MULTI-THREADED SERVER: Total Running Threads:  " << mTotalRunningThreads << endl;
      cout << "===============================================================" << endl;
      QThread::msleep(100);
    }
  }

  /*
  // Create objects on the stack
  QUdpSocket MasterUdpSocket;
  QHostAddress PeerAddress;
  uint16_t peer_port; // Ougoing Peer port, in case they're not using the default

  // Bind the socket to the well known port
  bindUdpSocket(MasterUdpSocket, mServerPort);

  char buf[1];
  cout << "Server Listening in UDP Port: " << mServerPort << endl;
  cout << "Waiting for client..." << endl;
  cout << "=======================================================" << endl;
  while ( !mStopped )
  {
    //cout << "WAITING........................." << endl;
    while ( MasterUdpSocket.hasPendingDatagrams() )
    {
      cout << "Received request from Client!" << endl;
      // Get Client IP Address and outgoing port from packet
      int rv = MasterUdpSocket.readDatagram(buf, 1, &PeerAddress, &peer_port);
      cout << "Peer Port in Server ==== " << peer_port << endl;
      if (rv < 0) { std::cerr << "ERROR: Bad UDP packet read..." << endl; }

      /// \todo Get number of channels in the client from header

      // check by comparing 32-bit addresses
      /// \todo Add the port number in the comparison
      cout << "peer_portpeer_portpeer_port === " << peer_port << endl;
      int id = isNewAddress(PeerAddress.toIPv4Address(), peer_port);

      //cout << "IDIDIDIDIDDID === " << id << endl;

      // If the address is new, create a new thread in the pool
      if (id >= 0) // old address is -1
      {
        // redirect port and spawn listener
        sendToPoolPrototype(id);
        // wait until one is complete before another spawns
        while (mJTWorker->isSpawning()) { QThread::msleep(10); }
        mTotalRunningThreads++;
        cout << "Total Running Threads:  " << mTotalRunningThreads << endl;
        cout << "=======================================================" << endl;
      }
      //cout << "ENDDDDDDDDDDDDDDDDDd === " << id << endl;
    }
    QThread::msleep(100);
  }
  */
}
Exemple #13
0
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;
                        }
                    }
                }
Exemple #14
0
/**
  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;

                // data already in buffer?
                if(pos + endMarkerSz + needMore <= readBytes)
                {
                    postData.append(input, pos,  endMarkerSz + needMore);
                }
                else
                {
                    TRACE_ERR(" TODO::: ############## - wait for more POST data");

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

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

                processRequest(req.c_str(), connID, resp, &postData);
            }

            // respond
            conn->write(resp.c_str(), resp.size());
            conn->flush();

            // next request possible?                                
            pos += endMarkerSz;  

            if(pos == input.size())
                break;

            offset = pos;
        }

        // ????? ??? ? ?? 

        // all messages read!
        break;
    }

    // all data read!
    return;
}
Exemple #15
0
int main(int argc, char** argv)
{
    QCoreApplication app(argc, argv);

    const QStringList args = app.arguments();
    QString arg_port;
    QString arg_server;
    QString arg_xmlFile;
    bool arg_crash = false;
    bool arg_garbage = false;
    uint arg_wait = 0;

    const QProcessEnvironment sysEnv = QProcessEnvironment::systemEnvironment();
    arg_xmlFile = sysEnv.value("QCIT_INPUT_FILE");

    for (int i = 1; i < args.size(); ++i) {
        const QString& arg = args.at(i);
        if (arg.startsWith(QLatin1String("--xml-socket="))) {
            arg_server = arg.mid(13, arg.indexOf(':') - 13);
            arg_port = arg.mid(13 + arg_server.length() + 1);
        } else if (args.size() > i + 1
                    && (args.at(i) == QLatin1String("-i")
                        || args.at(i) == QLatin1String("--xml-input"))) {
            arg_xmlFile = args.at(i+1);
            ++i;
        } else if (arg == QLatin1String("-c") || arg == QLatin1String("--crash")) {
            arg_crash = true;
        } else if (arg == QLatin1String("-g") || arg == QLatin1String("--garbage")) {
            arg_garbage = true;
        } else if (args.size() > i + 1 && (arg == QLatin1String("-w") || arg == QLatin1String("--wait"))) {
            bool ok;
            arg_wait = args.at(i+1).toUInt(&ok);
            if (!ok) {
                qerr << "ERROR: invalid wait time given" << args.at(i+1) << endl;
                usage(qerr);
                return 4;
            }
        } else if (args.at(i) == QLatin1String("--help") || args.at(i) == QLatin1String("-h")) {
            usage(qout);
            return 0;
        }
    }

    if (arg_xmlFile.isEmpty()) {
        qerr << "ERROR: no XML input file given" << endl;
        usage(qerr);
        return 1;
    }
    if (arg_server.isEmpty()) {
        qerr << "ERROR: no server given" << endl;
        usage(qerr);
        return 2;
    }
    if (arg_port.isEmpty()) {
        qerr << "ERROR: no port given" << endl;
        usage(qerr);
        return 3;
    }

    QFile xmlFile(arg_xmlFile);
    if (!xmlFile.exists() || !xmlFile.open(QIODevice::ReadOnly)) {
        qerr << "ERROR: invalid XML file" << endl;
        usage(qerr);
        return 10;
    }
    bool ok = false;
    quint16 port = arg_port.toUInt(&ok);
    if (!ok) {
        qerr << "ERROR: invalid port" << endl;
        usage(qerr);
        return 30;
    }

    QTcpSocket socket;
    socket.connectToHost(arg_server, port, QIODevice::WriteOnly);
    if (!socket.isOpen()) {
        qerr << "ERROR: could not open socket to server:" << arg_server << ":" << port << endl;
        usage(qerr);
        return 20;
    }
    if (!socket.waitForConnected()) {
        qerr << "ERROR: could not connect to socket: " << socket.errorString() << endl;
        return 21;
    }

    OutputGenerator generator(&socket, &xmlFile);
    QObject::connect(&generator, SIGNAL(finished()), &app, SLOT(quit()));
    generator.setCrashRandomly(arg_crash);
    generator.setOutputGarbage(arg_garbage);
    generator.setWait(arg_wait);

    return app.exec();
}
void getActiveCellCenters(NDArray& cellCenterValues, const QString &hostName, quint16 port, const qint32& caseId, const QString& porosityModel)
{
    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("GetActiveCellCenters %1 %2").arg(caseId).arg(porosityModel);
    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::shortTimeOutMilliSecs))
        {
            error((("Waiting for header: ") + socket.errorString()).toLatin1().data());
            return;
        }
    }

    // Read timestep count and blocksize

    quint64 activeCellCount;
    quint64 byteCount;

    socketStream >> activeCellCount;
    socketStream >> byteCount;

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

    dim_vector dv;
    dv.resize(2);
    dv(0) = activeCellCount;
    dv(1) = 3;

    cellCenterValues.resize(dv);

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

    quint64 bytesRead = 0;
    double* internalMatrixData = cellCenterValues.fortran_vec();
    bytesRead = socket.read((char*)(internalMatrixData), byteCount);

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

    return;
}
void TerminalMessageDialog::displayError(QAbstractSocket::SocketError)//显示错误
{
     QTcpSocket * tcpclient = (qobject_cast<QTcpSocket *>(sender()));
     qDebug() <<"tcpclient->errorString();"<< tcpclient->errorString();
}
Exemple #18
0
void VirtTcpC::onClientError(QAbstractSocket::SocketError error)
{
    QTcpSocket *sock = (QTcpSocket*)(sender());
    qDebug()<<error<<sock->errorString();
}
Exemple #19
0
//! [4]
void FortuneThread::run()
{
    mutex.lock();
//! [4] //! [5]
    QString serverName = hostName;
    quint16 serverPort = port;
    mutex.unlock();
//! [5]

//! [6]
    while (!quit) {
//! [7]
        const int Timeout = 5 * 1000;

        QTcpSocket socket;
        socket.connectToHost(serverName, serverPort);
//! [6] //! [8]

        if (!socket.waitForConnected(Timeout)) {
            emit error(socket.error(), socket.errorString());
            return;
        }
//! [8] //! [9]

        while (socket.bytesAvailable() < (int)sizeof(quint16)) {
            if (!socket.waitForReadyRead(Timeout)) {
                emit error(socket.error(), socket.errorString());
                return;
            }
//! [9] //! [10]
        }
//! [10] //! [11]

        quint16 blockSize;
        QDataStream in(&socket);
        in.setVersion(QDataStream::Qt_4_0);
        in >> blockSize;
//! [11] //! [12]

        while (socket.bytesAvailable() < blockSize) {
            if (!socket.waitForReadyRead(Timeout)) {
                emit error(socket.error(), socket.errorString());
                return;
            }
//! [12] //! [13]
        }
//! [13] //! [14]

        mutex.lock();
        QString fortune;
        in >> fortune;
        emit newFortune(fortune);
//! [7] //! [14] //! [15]

        cond.wait(&mutex);
        serverName = hostName;
        serverPort = port;
        mutex.unlock();
    }
//! [15]
}
void 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::longTimeOutMilliSecs))
        {
            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);

    double* internalMatrixData = cellCornerValues.fortran_vec();
    QStringList errorMessages;
    if (!RiaSocketDataTransfer::readBlockDataFromSocket(&socket, (char*)(internalMatrixData), byteCount, errorMessages))
    {
        for (int i = 0; i < errorMessages.size(); i++)
        {
            error(errorMessages[i].toLatin1().data());
        }

        OCTAVE_QUIT;
    }

    return;
}
void WindowSystem::handleConnectionError()
{
    QTcpSocket *connection = qobject_cast<QTcpSocket*>(sender());
    qWarning() << connection->errorString();
}
void getMainGridDimensions(int32NDArray& gridDimensions, const QString &hostName, quint16 port, QString caseName)
{
    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("GetMainGridDimensions ");
    command += caseName;
    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)(3*sizeof(quint64)))
    {
        if (!socket.waitForReadyRead(Timeout))
        {
            error((("Wating for header: ") + socket.errorString()).toLatin1().data());
            return;
        }
    }

    // Read timestep count and blocksize

    quint64 iCount;
    quint64 jCount;
    quint64 kCount;

    socketStream >> iCount;
    socketStream >> jCount;
    socketStream >> kCount;

    dim_vector dv (1, 1);
    dv(0) = 3;

    gridDimensions.resize(dv);
    gridDimensions(0) = iCount;
    gridDimensions(1) = jCount;
    gridDimensions(2) = kCount;


    QString tmp = QString("riGetMainGridDimensions : Read main grid dimensions");
    if (caseName.isEmpty())
    {
        tmp += QString(" from active case.");
    }
    else
    {
        tmp += QString(" from %1.").arg(caseName);
    }
    octave_stdout << tmp.toStdString() << " Dimensions: " << iCount << ", " << jCount << ", " << kCount << std::endl;

    return;
}
Exemple #23
0
void getDynamicNNCValues(Matrix& propertyFrames, const QString &serverName, quint16 serverPort,
                         const qint64& caseId, QString propertyName, const int32NDArray& requestedTimeSteps)
{
    QTcpSocket socket;
    socket.connectToHost(serverName, serverPort);

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

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

    // Create command as a string with arguments , and send it:
    QString command;
    command += "GetDynamicNNCValues " + QString::number(caseId) + " " + propertyName;

    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();

    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 header: ") + socket.errorString()).toLatin1().data());
            return;
        }
    }

    // Read connection count and timestep count
    quint64 connectionCount;
    quint64 timestepCount;

    socketStream >> connectionCount;
    socketStream >> timestepCount;

    propertyFrames.resize(connectionCount, timestepCount);

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

    quint64 totalByteCount = timestepCount * connectionCount * sizeof(double);

    double* internalMatrixData = propertyFrames.fortran_vec();
    QStringList errorMessages;
    if (!RiaSocketDataTransfer::readBlockDataFromSocket(&socket, (char*)(internalMatrixData), totalByteCount, errorMessages))
    {
        for (int i = 0; i < errorMessages.size(); i++)
        {
            error(errorMessages[i].toLatin1().data());
        }

        return;
    }

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

    if (caseId < 0)
    {
        tmp += QString(" from current case.");
    }
    else
    {
        tmp += QString(" from case with Id: %1.").arg(caseId);
    }
    octave_stdout << tmp.toStdString() << " Connections: " << connectionCount << ", Time steps : " << timestepCount << std::endl;

    return;
}
void getGridProperty(NDArray& propertyFrames, const QString &serverName, quint16 serverPort,
                        const int& caseId, int gridIdx, QString propertyName, const int32NDArray& requestedTimeSteps, QString porosityModel)
{
    QTcpSocket socket;
    socket.connectToHost(serverName, serverPort);

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

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

    // Create command as a string with arguments , and send it:

    QString command;
    command += "GetGridProperty " + QString::number(caseId) + " " + QString::number(gridIdx) + " " + propertyName + " " + porosityModel;

    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();

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

    // Get response. First wait for the header

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

    // Read sizes

    quint64 totalByteCount;
    quint64 cellCountI;
    quint64 cellCountJ;
    quint64 cellCountK;
    quint64 timestepCount;

    socketStream >> cellCountI;
    socketStream >> cellCountJ;
    socketStream >> cellCountK;
    socketStream >> timestepCount;

    totalByteCount = cellCountI*cellCountJ*cellCountK*timestepCount*sizeof(double);
    if (!(totalByteCount))
    {
        error ("Could not find the requested data in ResInsight");
        return;
    }

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

    propertyFrames.resize(dv);


    // Wait for available data

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

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

    // Raw data transfer. Faster.
    bytesRead = socket.read((char*)(internalMatrixData ), totalByteCount);

    if ((int)totalByteCount != bytesRead)
    {
        error("Could not read binary double data properly from socket");
    }

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

    if (caseId < 0)
    {
        tmp += QString(" from current case,");
    }
    else
    {
        tmp += QString(" from case with Id: %1,").arg(caseId);
    }

    tmp += QString(" grid index: %1, ").arg(gridIdx);

    octave_stdout << tmp.toStdString() << " I, J, K " << cellCountI << ", " << cellCountJ << ", " << cellCountK << ", Timesteps : " << timestepCount << std::endl;

    return;
}
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;
}