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


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

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


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

示例1: fetchFeedData

int UCHome_Main_SiteConst::fetchFeedData() 
{
    q_debug()<<"impled";
    
    QTcpSocket *sock = NULL;

    sock = new QTcpSocket();
    
    sock->connectToHost(this->host, this->port);
    if(!sock->waitForConnected()) {
        q_debug()<<"Connect error";
        return FETCH_FEED_ERROR;
    }
    
    QString request;
    request = 
        QString(
                "GET %1 HTTP/1.1\r\n"
                "Host: uchome.developer.manyou.com\r\n"
                "User-Agent: Opera/9.62 (X11; Linux i686; U; zh-cn)\r\n"
                "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n"
                "Accept-Language: zh-cn,zh;q=0.5\r\n"
                "Accept-Charset: gb2312,utf-8;q=0.7,*;q=0.7\r\n"
                //"Keep-Alive: 300\r\n"
                //"Connection: keep-alive\r\n"
                "Connection: close\r\n"
                "Cookie: %2\r\n"
                "\r\n"
                )
        .arg(this->feed_url, this->cookies);

    q_debug()<<request;
    sock->write(request.toAscii());
    if(!sock->waitForBytesWritten()) {
        q_debug()<<"Write error";
        return FETCH_FEED_ERROR;
    }

    char header[8192] = {0} ;
    char b2[2] = {0};
    char *bp = &header[0];
    char *tp = bp;
    qint64 rlen = 0;
    qint64 oklen = 0;

    if(!sock->waitForReadyRead()) {
        q_debug()<<"wait read error";
        return LOGIN_ERROR;
    }

    while(true) {
        oklen = sock->bytesAvailable();
        if(oklen < 0 ) {
            q_debug()<<"wait read errorsdfjsdifsdifsdifj";
        }
        while(oklen-- > 0) {
            rlen = sock->read(b2, 1);
            *tp++ = b2[0];
            if(tp - bp > 4 && strncmp(tp-4, "\r\n\r\n", 4) == 0) {
                break;
            }
        }
        if(strncmp(tp-4, "\r\n\r\n", 4) == 0) {
            break;
        }
    }
    //parse header, got file length
    QString html_header = header;

    QStringList header_lines = QString(header).split("\r\n");
    qint64 content_length = -1;
    for(int i = 0; i < header_lines.count(); i ++) {
        if(header_lines.at(i).startsWith("Content-length")) {
            content_length = header_lines.at(i).split(":").at(1).trimmed().toLongLong();
        }
    }
    
    if(content_length == -1) {
        q_debug()<<"Unknown content-length for header:"<< html_header;
        //return FETCH_FEED_ERROR;
    }

    QByteArray html;
    QByteArray hb ;
    while(true) {
        oklen = sock->bytesAvailable();
        if(oklen > 0) {
            hb= sock->readAll();
            html += hb;
        }else if(oklen == 0) {
            if(!sock->waitForReadyRead()) {
                q_debug()<<"wait read error";
                break;
            }
        }else{
            q_debug()<<"bytesAvalibale < 0";
            break;
        }
    }
    
//.........这里部分代码省略.........
开发者ID:kitech,项目名称:snsnotify,代码行数:101,代码来源:uch_mydev_feed.cpp

示例2: run

void AndroidRetracer::run()
{
    m_androidUtils.reloadAdb();
    QString errorStr;
    bool setupRet;
    QMetaObject::invokeMethod(this, "setup", Qt::BlockingQueuedConnection,
                              Q_RETURN_ARG(bool, setupRet),
                              Q_ARG(QString *, &errorStr));

    if (!setupRet) {
        emit finished(errorStr);
        return;
    }

    if (!m_androidUtils.runAdb(QStringList() << _("shell") << _("am") << _("start") << _("-n") << packageName + activityName)) {
        emit finished(tr("Can't start apitrace application"));
        return;
    }
    QByteArray which;
    if (!m_androidUtils.runAdb(QStringList() << _("shell") << _("readlink") << _("$(which ps)") , &which)) {
        emit finished(tr("Can't start adb"));
        return;
    }

    bool isBusyBox = which.startsWith("busybox");
    QStringList psArgs;
    psArgs << _("shell") << _("ps");
    if (isBusyBox)
        psArgs << _("-w");

    qint64 processPID;
    bool wasStarted = false;
    QTime startTime;
    startTime.start();

    QTcpSocket stdoutSocket;
    QTcpSocket stderrSocket;

    ImageHash thumbnails;

    QVariantMap parsedJson;
    trace::Profile* profile = isProfiling() ? new trace::Profile() : NULL;

    QList<ApiTraceError> errors;
    QRegExp regexp("(^\\d+): +(\\b\\w+\\b): ([^\\r\\n]+)[\\r\\n]*$");

    QString msg = QLatin1String("Replay finished!");
    QByteArray ubjsonBuffer;
    QByteArray outputBuffer;
    bool keepGoing = true;
    while(keepGoing) {
        if (!wasStarted || startTime.elapsed() > 1000) {
            QByteArray psOut;
            m_androidUtils.runAdb(psArgs, &psOut);
            processPID = extractPid(psOut);
            if (wasStarted)
                startTime.restart();
        }

        if (processPID == -1) {
            if (wasStarted) {
                break;
            } else {
                if (startTime.elapsed() > 3000) { // wait 3 seconds to start
                    emit finished(tr("Unable to start retrace on device."));
                    return;
                }
            }
            msleep(100);
            continue;
        }

        // we have a valid pid, it means the application started
        if (!wasStarted) {
            // connect the sockets
            int tries = 0;
            do {
                stdoutSocket.connectToHost(QHostAddress::LocalHost, m_stdoutPort);
            } while (!stdoutSocket.waitForConnected(100) && ++tries < 10);
            if (stdoutSocket.state() != QAbstractSocket::ConnectedState) {
                emit finished(tr("Can't connect to stdout socket."));
                return;
            }

            // Android doesn't suport GPU and PPD profiling (at leats not on my devices)
            //setProfiling(false, isProfilingCpu(), false);

            QString args = (retraceArguments() << m_androdiFileName).join(" ") + _("\n");
            stdoutSocket.write(args.toUtf8());
            if (!stdoutSocket.waitForBytesWritten()) {
                emit finished(tr("Can't send params."));
                return;
            }


            stderrSocket.connectToHost(QHostAddress::LocalHost, m_stderrPort);
            stderrSocket.waitForConnected(100);
            if (stderrSocket.state() != QAbstractSocket::ConnectedState) {
                emit finished(tr("Can't connect to stderr socket."));
                return;
//.........这里部分代码省略.........
开发者ID:Dhanasekahar,项目名称:apitrace,代码行数:101,代码来源:androidretracer.cpp

示例3: onSocketReadyRead

void HttpProxy::onSocketReadyRead()
{
    QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
    QTcpSocket *proxySocket = nullptr;

    QByteArray reqData = socket->readAll();
    int pos = reqData.indexOf("\r\n");
    QByteArray reqLine = reqData.left(pos);
    reqData.remove(0, pos + 2);

    QList<QByteArray> entries = reqLine.split(' ');
    QByteArray method = entries.value(0);
    QByteArray address = entries.value(1);
    QByteArray version = entries.value(2);

    QString host;
    quint16 port;
    QString key;

    if (method != "CONNECT") {
        QUrl url = QUrl::fromEncoded(address);
        if (!url.isValid()) {
            emit info("Invalid URL: " + url.toString());
            socket->disconnectFromHost();
            return;
        }
        host = url.host();
        port = url.port(80);
        QString req = url.path();
        if (url.hasQuery()) {
            req.append('?').append(url.query());
        }
        reqLine = method + " " + req.toUtf8() + " " + version + "\r\n";
        reqData.prepend(reqLine);
        key = host + ':' + QString::number(port);
        proxySocket = socket->findChild<QTcpSocket *>(key);
        if (proxySocket) {
            proxySocket->write(reqData);
            return;//if we find an existing socket, then use it and return
        }
    } else {//CONNECT method
        /*
         * according to http://tools.ietf.org/html/draft-luotonen-ssl-tunneling-03
         * the first line would CONNECT HOST:PORT VERSION
         */
        QList<QByteArray> host_port_list = address.split(':');
        host = QString(host_port_list.first());
        port = host_port_list.last().toUShort();
    }

    proxySocket = new QTcpSocket(socket);
    proxySocket->setProxy(upstreamProxy);
    if (method != "CONNECT") {
        proxySocket->setObjectName(key);
        proxySocket->setProperty("reqData", reqData);
        connect (proxySocket, &QTcpSocket::connected, this, &HttpProxy::onProxySocketConnected);
        connect (proxySocket, &QTcpSocket::readyRead, this, &HttpProxy::onProxySocketReadyRead);
    } else {
        connect (proxySocket, &QTcpSocket::connected, this, &HttpProxy::onProxySocketConnectedHttps);
    }
    connect (proxySocket, &QTcpSocket::disconnected, proxySocket, &QTcpSocket::deleteLater);
    connect (proxySocket, static_cast<void (QTcpSocket::*)(QAbstractSocket::SocketError)>(&QTcpSocket::error), this, &HttpProxy::onSocketError);
    proxySocket->connectToHost(host, port);
}
开发者ID:nazhenhuiyi,项目名称:libQtShadowsocks,代码行数:64,代码来源:httpproxy.cpp

示例4: setEclipseProperty

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;
}
开发者ID:OPM,项目名称:ResInsight,代码行数:92,代码来源:riSetActiveCellProperty.cpp

示例5: sendTrackerRequest

QByteArray BtQt::sendTrackerRequest(BtTrackerRequest const &req, QUrl trackerUrl)
{
    if(trackerUrl.scheme() != "http") {
        /* There may be "udp" or "https" or other schemes,
         * but not supported now */
        qDebug() << "Request to announce" << trackerUrl;
        qDebug() << "Protocol not supported!";
        return QByteArray();
    }
    /* For the reason that QUrl has used RFC3986 instead of RFC 1738,
     * I have to emulate an HTTP GET request using tcp socket. */
    QTcpSocket socket;
    QString host = trackerUrl.host();
    quint16 port = trackerUrl.port(80);
#ifndef QT_NO_DEBUG
    qDebug() << "Host: " << host;
    qDebug() << "Port: " << port;
#endif // QT_NO_DEBUG
    /*
     *QString host = trackerUrl.toEncoded(QUrl::RemoveScheme | QUrl::RemovePath
     *        | QUrl::RemoveAuthority);
     */
    socket.connectToHost(host, port);
    if(!socket.waitForConnected(1000)) {
        qDebug() << "Can not establish tcp connection to"  << host + ":" + QString::number(port);
        throw -1;
    }
    socket.setSocketOption(QAbstractSocket::KeepAliveOption, 1);

    /* HTTP 1.1 header, for more information please go to RFC2616 */
    QByteArray header;
    header.append("HOST: " + host + ":" + QString::number(port) + "\r\n");
    header.append("User-Agent: " + BtQt::application + " " + BtQt::version + "\r\n");
    header.append("Accept: */*\r\n");
    header.append("Connection: Keep-Alive\r\n");
    header.append("\r\n");

    QByteArray string;
    if(trackerUrl.hasQuery()) {
        string = "GET " + trackerUrl.toEncoded(QUrl::RemoveScheme | QUrl::RemoveAuthority) + '&' + req.toRequestData() + " HTTP/1.1\r\n";
    } else {
        string = "GET " + trackerUrl.toEncoded(QUrl::RemoveScheme | QUrl::RemoveAuthority) + '?' + req.toRequestData() + " HTTP/1.1\r\n";
    }

#ifndef QT_NO_DEBUG
    qDebug() << "Header: " << header;
    qDebug() << "String: " << string;
#endif // QT_NO_DEBUG

    socket.write(string + header);

    if(!socket.waitForReadyRead(1000)) {
        qDebug() << "There were some error occured or possibly time out! Can not get reply!";
        throw -1;
    }
    QByteArray trackerReply = socket.readAll();
    if(trackerReply.isEmpty()) {
        qDebug() << "Warnning! We got an empty reply!";
    }

    /* Get the reply data */
    int replyIdx = trackerReply.indexOf("\r\n\r\n") + 4;

    return trackerReply.mid(replyIdx);
}
开发者ID:ArkBriar,项目名称:BtQt,代码行数:65,代码来源:BtTracker.cpp

示例6: main

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();
}
开发者ID:CNOT,项目名称:julia-studio,代码行数:93,代码来源:main.cpp

示例7: startTests

void LockTestClient::startTests()
{
    QTcpSocket socket;
    socket.connectToHost ( "localhost", 55555);
    char control;
    
    #define GetNextCommand()      if(socket.waitForReadyRead (-1) )\
                                                        {\
                                                            if(socket.bytesAvailable() > 1)\
                                                                qDebug()<<"Something is wrong here";\
                                                            socket.getChar(&control);\
                                                            if(control == 'a')\
                                                            {\
                                                                socket.disconnectFromHost();\
                                                                return;\
                                                            }\
                                                            if(control != 'n')\
                                                            { \
                                                                 qDebug()<<"Wrong control command";\
                                                            }\
                                                        }
    
    if(socket.waitForConnected (-1))
    {
        QFile file("lock.file");
        
        if(!file.open(QIODevice::ReadWrite))
        {
            qDebug()<<"Could not open lockfile";
            return;
        }
        
        if(1)
        {
            GetNextCommand();
            //Trying to readlock the same region
            QxtFileLock lock(&file,0x10,20,QxtFileLock::ReadLock);
            if(lock.lock())
                socket.putChar('s');    //s for success f for fail
            else
                socket.putChar('f');
            socket.waitForBytesWritten(-1);
        }
        
        if(1)
        {
            GetNextCommand();
             //Trying to lock the same region with different locks
            QxtFileLock lock(&file,0x10,20,QxtFileLock::WriteLock); 
            
            if(!lock.lock())
                socket.putChar('s');    //s for success f for fail
            else
                socket.putChar('f');
            socket.waitForBytesWritten(-1);
        }
        
        if(1)
        {
            GetNextCommand();
             //Trying to writelock the same region
            QxtFileLock lock(&file,0x10,20,QxtFileLock::WriteLock); 
            
            if(!lock.lock())
                socket.putChar('s');    //s for success f for fail
            else
                socket.putChar('f');
            socket.waitForBytesWritten(-1);
        }
        
        if(1)
        {
            GetNextCommand();
             //Trying to writelock different regions
            QxtFileLock lock(&file,0x10+21,20,QxtFileLock::WriteLock); 
            
            if(lock.lock())
                socket.putChar('s');    //s for success f for fail
            else
                socket.putChar('f');
            socket.waitForBytesWritten(-1);
        }
        
    }
}
开发者ID:develnk,项目名称:qxtweb-qt5,代码行数:85,代码来源:locktestclient.cpp

示例8: init

/*!
    \internal
*/
void QInterProcessChannel::init()
{
    while ( isRunning() )
        quit();
    
    if ( pServerTimer )
    {
        pServerTimer->stop();
        delete pServerTimer;
        pServerTimer = 0;
    }
    
    bool ok = true;
    
    m_port = 0;
    m_addr = QHostAddress::LocalHost;
    
    pServer = new QTcpServer(this);
    pServer->listen(m_addr, m_port);
    
    connect(pServer , SIGNAL( newConnection() ),
            this    , SLOT  ( connection() ) );
    
    if ( QFile::exists(rcFile) )
    {
        /*
            found a server config file, let us assume it is from a running server
        */
        //qDebug("checking old server...");
        
        QSettings conf(rcFile, QSettings::IniFormat);
        
        m_port = conf.value("port").toUInt();
        m_addr = QHostAddress(conf.value("address").toString());
        
        QTcpSocket *pSocket = new QTcpSocket(this);
        
        if ( !m_addr.isNull() && m_port )
        {
            pSocket->connectToHost(m_addr, m_port);
            ok = pSocket->waitForConnected(WAIT_TIMEOUT);
            
            if ( ok ) ok &= (bool)pSocket->write("--check");
            if ( ok ) ok &= (bool)pSocket->waitForBytesWritten(WAIT_TIMEOUT);
            if ( ok ) ok &= (bool)pSocket->waitForReadyRead(WAIT_TIMEOUT);
            if ( ok ) ok &= (pSocket->readAll() == "[ALIVE]");
            
        } else {
            ok = false;
        }
        
        if ( !ok )
        {
            QFile::remove(rcFile);
        }
        
        pSocket->disconnectFromHost();
        delete pSocket;
    }
    
    if ( !QFile::exists(rcFile) )
    {
        // no server found... Create one
        //qDebug("setting up new server...");
        
        m_port = pServer->serverPort();
        m_addr = pServer->serverAddress();
        
        QSettings conf(rcFile, QSettings::IniFormat);
        conf.setValue("port", m_port);
        conf.setValue("address", m_addr.toString());
        
        emit gotServerRole();
        emit serverRoleChanged(true);
    } else {
        // server found we'll hook on it later on...
        pServer->close();
        pServer = 0;
        
        emit serverRoleChanged(false);
    }
    
    start();
}
开发者ID:ppekala,项目名称:qnapi,代码行数:87,代码来源:qinterprocesschannel.cpp

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

示例10: getActiveCellCenters

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;
}
开发者ID:renjianshuiguo,项目名称:ResInsight,代码行数:79,代码来源:riGetActiveCellCenters.cpp

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

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

示例13: 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:CodeDJ,项目名称:qt5-hidpi,代码行数:62,代码来源:fortunethread.cpp

示例14: main

int main(int argc, char* argv[])
{
  terrama2::core::TerraMA2Init terramaRaii("example", 0);
  QCoreApplication app(argc, argv);

  QJsonObject obj;
  QJsonArray providersArray;
  providersArray.push_back(terrama2::core::toJson(buildInputProvider()));
  obj.insert("DataProviders", providersArray);

  QJsonArray seriesArray;
  seriesArray.push_back(terrama2::core::toJson(buildInputDataSeries()));
  obj.insert("DataSeries", seriesArray);

  QJsonDocument doc(obj);

  std::shared_ptr<terrama2::core::DataManager> dataManager = std::make_shared<MockDataManager>();
  terrama2::core::TcpManager tcpManager(dataManager, std::weak_ptr<terrama2::core::ProcessLogger>());
  tcpManager.listen(QHostAddress::Any, 30000);

  QByteArray bytearray;
  QDataStream out(&bytearray, QIODevice::WriteOnly);


  QJsonObject logDb;
  logDb.insert("PG_HOST", QString::fromStdString(TERRAMA2_DATABASE_HOST));
  logDb.insert("PG_PORT", QString::fromStdString(TERRAMA2_DATABASE_PORT));
  logDb.insert("PG_USER", QString::fromStdString(TERRAMA2_DATABASE_USERNAME));
  logDb.insert("PG_PASSWORD", QString::fromStdString(TERRAMA2_DATABASE_PASSWORD));
  logDb.insert("PG_DB_NAME", QString::fromStdString(TERRAMA2_DATABASE_DBNAME));

  QJsonObject serviceConf;
  serviceConf.insert("instance_id", 1);
  serviceConf.insert("log_database", logDb);

  QJsonDocument serviceConfDoc(serviceConf);
  QByteArray serviceConfBytearray;
  QDataStream out2(&serviceConfBytearray, QIODevice::WriteOnly);
  auto jsonServiceConf = serviceConfDoc.toJson(QJsonDocument::Compact);
  out2 << static_cast<uint32_t>(0);
  out2 << static_cast<uint32_t>(terrama2::core::TcpSignal::UPDATE_SERVICE_SIGNAL);
  out2 << jsonServiceConf;
  serviceConfBytearray.remove(8, 4);//Remove QByteArray header
  out2.device()->seek(0);
  out2 << static_cast<uint32_t>(serviceConfBytearray.size() - sizeof(uint32_t));



  auto json = doc.toJson(QJsonDocument::Compact);
  out << static_cast<uint32_t>(0);
  out << static_cast<uint32_t>(terrama2::core::TcpSignal::ADD_DATA_SIGNAL);
  out << json;
  bytearray.remove(8, 4);//Remove QByteArray header
  out.device()->seek(0);
  out << static_cast<uint32_t>(bytearray.size() - sizeof(uint32_t));



  QTcpSocket socket;
  socket.connectToHost("localhost", 30000);
  socket.write(serviceConfBytearray);
  socket.waitForBytesWritten();
  socket.write(bytearray);

  QTimer timer;
  QObject::connect(&timer, SIGNAL(timeout()), QCoreApplication::instance(), SLOT(quit()));
  timer.start(10000);
  app.exec();

  

  return 0;
}
开发者ID:raphaelrpl,项目名称:terrama2,代码行数:73,代码来源:ListenToTcp.cpp

示例15: reset

void BasicEmulator::reset()
{
    LOG_DEBUG("End of BasicEmulator::reset");

    // Connect to emulator daemon
    QTcpSocket socket;
    socket.connectToHost(QHostAddress(m_addr), m_port);
    if( !socket.waitForConnected(3 * 1000))
    {
        LOG_ERROR(QString("Cannot connect to emulator daemon @ %1:%2")
            .arg(m_addr).arg(m_port));
        return;
    }
    
    // Send request
    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);
    out << (quint32)0;
    out << QString("Basic");
    out << QString("RESET");
    out.device()->seek(0);
    out << (quint32)(block.size() - 4);

    socket.write(block);
    socket.waitForBytesWritten(-1);
    
    // Receive response
    while( socket.bytesAvailable() < 4 )
    {
        if( !socket.waitForReadyRead(5 * 1000))
        {
            LOG_WARN("BasicEmulator reset timed out");
            return;
        }
    }
    
    quint32 blockSize;
    QDataStream in(&socket);
    in >> blockSize;
    
    while( socket.bytesAvailable() < blockSize )
    {
        if( !socket.waitForReadyRead(5 * 1000))
        {
            LOG_WARN("BasicEmulator reset timed out");
            return;
        }
    }
    
    bool ok;
    QString description;
    in >> ok >> description;
    
    // Display result
    if( ok )
    {
        LOG_INFO("Parameters successfully reset");
        LOG_INFO(QString("Description: %1").arg(description));
        
        m_params.clear();
    }
    else
    {
        LOG_WARN("Parameter reset failed");
        LOG_WARN(QString("Description: %1").arg(description));
    }

    // Close connection
    socket.close();
    LOG_DEBUG("End of BasicEmulator::reset");
}
开发者ID:windy32,项目名称:algts,代码行数:71,代码来源:basic-emulator.cpp


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