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


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

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


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

示例1: processLine

QString ConnectionThread::processLine(QTcpSocket & sock,
                                      const QString & line)
{
    Debug() << "Got Line: " << line;
    QStringList toks = line.split(QRegExp("\\s+"), QString::SkipEmptyParts);
    if (toks.size() < 1) return QString::null;
    QString cmd = toks.front();
    toks.pop_front();
    cmd = cmd.toUpper();
    if (cmd == "NOOP") {
        return ""; // noop command alwasy prints OK -- used to test server connectivity and for keepaliveage, etc
    } else if (cmd == "GETTIME") {
        return QString::number(getTime(), 'f', 9);
    } else if (cmd == "GETFRAMENUM") {
        StimPlugin *p = stimApp()->glWin()->runningPlugin();
        if (p) {
            return QString::number(p->getFrameNum());
        } else {
            Error() << "GETFRAMENUM command received but no plugin was running.";
        }
    } else if (cmd == "GETHWFRAMENUM") {
        GetHWFrameCountEvent *e = new GetHWFrameCountEvent();
        GetSetData *d = e->d;
        stimApp()->postEvent(this, e);
        unsigned hwfc = d->getReply<unsigned>();
        delete d;
        return QString::number(hwfc);
    } else if (cmd == "GETREFRESHRATE") {
        unsigned rate = stimApp()->refreshRate();
        return QString::number(rate);
    } else if (cmd == "GETCURRENTRSEED") {
        int s = stimApp()->glWin() 
			    ?  (stimApp()->glWin()->runningPlugin() 
				    ? stimApp()->glWin()->runningPlugin()->currentRSeed() 
				    : 0)
				: 0;
        return QString::number(s);
    } else if (cmd == "GETWIDTH") {
        return QString::number(stimApp()->glWin()->width());
    } else if (cmd == "GETHEIGHT") {
        return QString::number(stimApp()->glWin()->height());
    } else if (cmd == "GETFRAME" && toks.size()) {
        bool ok;
        unsigned framenum = toks[0].toUInt(&ok), numFrames = 1;
		Vec2i co, cs, ds; // params 3,4,5,6,7,8 are crop-origin-x, crop-origin-y, crop-size-width, crop-size-height, downsample-factor-x, downsample-factor-y
        toks.pop_front();
		if (toks.size()) {
			bool ok2;
			numFrames = toks.front().toUInt(&ok2);
			if (ok2) toks.pop_front();
			if (!ok2 || numFrames < 1) numFrames = 1;
			Vec2i *vp[] = { &co, &cs, &ds, 0 };
			for (Vec2i **vcur = vp; *vcur; ++vcur) {				
				Vec2i & v = **vcur;
				v.x = toks.size() ? toks.front().toUInt(&ok2) : 0;
				if (ok2) toks.pop_front();
				if (!ok2 || v.x < 0) v.x = 0;
				v.y = toks.size() ? toks.front().toUInt(&ok2) : 0;
				if (ok2) toks.pop_front();
				if (!ok2 || v.y < 0) v.y = 0;
			}
		}
		if (!ds.x) ds.x = 1;
		if (!ds.y) ds.y = 1;
        int datatype = GL_UNSIGNED_BYTE;
        if (toks.size()) {
            QString s = toks.join(" ").toUpper().trimmed();
            if (s == "BYTE") datatype = GL_BYTE;
            else if (s == "UNSIGNED BYTE") datatype = GL_UNSIGNED_BYTE;
            else if (s == "SHORT") datatype = GL_SHORT;
            else if (s == "UNSIGNED SHORT") datatype = GL_UNSIGNED_SHORT;
            else if (s == "INT") datatype = GL_INT;
            else if (s == "UNSIGNED INT") datatype = GL_UNSIGNED_INT;
            else if (s == "FLOAT") datatype = GL_FLOAT;
            else {
                Error() << "GETFRAME command invalid datatype `" << s << "'.";
                return QString::null;
            }
        }
        if (ok) {
            GetFrameEvent *e = new GetFrameEvent(framenum, numFrames, co, cs, ds, datatype);
            GetSetData *d = e->d;
            stimApp()->postEvent(this, e);
			const double tgen0 = getTime();
            QList<QByteArray> frames (d->getReply<QList<QByteArray> >());
            delete d;
            if (!frames.isEmpty()) {
				const unsigned long fbytes = frames.count()*frames.front().size();
				Debug() << "Generating " << frames.count() << " frames (" << fbytes << " bytes) took " << getTime()-tgen0 << " secs";
                sock.write((QString("BINARY DATA ") + QString::number(fbytes) + "\n").toUtf8());
				const double t0 = getTime();
				for (QList<QByteArray>::const_iterator it = frames.begin(); it != frames.end(); ++it)
					sock.write(*it);
				Debug() << "Sending " << numFrames << " frames (" << fbytes << " bytes) took " << getTime()-t0 << " secs";
                return "";
            }
        }
    } else if (cmd == "LIST") {
        QList<QString> lst = stimApp()->glWin()->plugins();
        QString ret;
//.........这里部分代码省略.........
开发者ID:cculianu,项目名称:StimulateOpenGL_II,代码行数:101,代码来源:ConnectionThread.cpp

示例2: main

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

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

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

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

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

    while(!quit){

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

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

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

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

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

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

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

示例3: s

/** A file is requested by the host
  *
  * This function is called when the client retirieve a file. The file
  * is sent to the client from the \c uploaded directory.
  *
  * \param filename The filename without path
  *
  */
void RainbruRPG::Network::Ftp::FtpTransfer::
commandRETR(const QString& filename){
  LOGI("Sending file...");
  QString s("Sending file ");
  s+=filename;
  emit(log(s));
  LOGI(s.toLatin1());
  nextCommand=FTC_RETR;

  // Get the absolute filename
  GlobalURI gu;
  std::string stdFilename(filename.toLatin1());
  std::string fullFileName=gu.getUploadFile(stdFilename);
  nextFilename=filename;
  nextOnlyFilename=filename;

  LOGCATS("Opening file '");
  LOGCATS(fullFileName.c_str());
  LOGCAT();

  QFile f(fullFileName.c_str());
  QIODevice::OpenMode om;

  // We are in Binary mode
  if (transferType==FTT_BINARY){
    om=QIODevice::ReadOnly;
  }
  // We are in ASCII mode
  else if (transferType==FTT_ASCII){
    om=QIODevice::ReadOnly|QIODevice::Text;
  }

  if(f.open(om)){
    QTcpSocket sock;
    if (waitForConnection(&sock)){
      emit(startTransferFile(filename, f.size()));
      int rep=0;
      
      while (!f.atEnd()){
	rep=sock.write(f.read(MAX_READ_LENGTH));
	if (rep==-1){
	  LOGE("An error occured during RETR command");
	  break;
	}
	else{
	  LOGCATS("Writing ");
	  LOGCATI(rep);
	  LOGCATS(" bytes");
	  LOGCAT();
	  
	  sock.waitForBytesWritten(3000);
	}
      }
      
      // Transfer complete
      emit(log("Transfer channel closed"));
      emit(transferComplete(filename));
      sock.disconnectFromHost();
      LOGI("Transfer complete");
      f.close();

    }
  }
  else{
    emit(log("An error occured during opening file :"));
    QFile::FileError fe=f.error();

    QString feText;
    if (fe==QFile::OpenError){
      feText=("5 The file could not be opened.");
    }
    else{
      feText.setNum(fe);
    }
    emit(log(feText));
  }
}
开发者ID:dreamsxin,项目名称:rainbrurpg,代码行数:85,代码来源:ftptransfer.cpp

示例4: processDeviceCommandSocket

void CClientApp::processDeviceCommandSocket()
{
    QTcpSocket *socket = deviceCmdServer->nextPendingConnection();

    QString kText("Recieve TCP Socket\n");
    Q_EMIT m_pSender->commandReturned(kText, false);

    QObject::connect(socket, &QTcpSocket::readyRead, [=]
    {
        QByteArray byteArray = socket->readAll();
        QJsonDocument jsonDoc = QJsonDocument::fromJson(byteArray);
        QJsonObject jsonObj = jsonDoc.object();

        QString command = jsonObj["command"].toString();

        QString retJsonString;

        QJsonObject retJsonObj;

        QString kText("Recieve Cmd: " + command + "\n");

        if (command == "supportCmds")
        {
            retJsonObj.insert("status", 200);
            QJsonArray cmdArray;
            /*
            QJsonObject cmdObj1;
            cmdObj1.insert("command", "adjustTemperature");
            cmdObj1.insert("command_displayName", "Set Temperature");
            cmdObj1.insert("param_type", "integer");
            cmdObj1.insert("param_max", "100");
            cmdObj1.insert("param_min", "20");

            QJsonObject cmdObj2;
            cmdObj2.insert("command", "query");
            cmdObj2.insert("command_displayName", "Query Status");
            cmdObj2.insert("param_type", "none");

            cmdArray.append(cmdObj1);
            cmdArray.append(cmdObj2);
            */
            retJsonObj.insert("SupportCmds", cmdArray);

            connected = true;
        }
        else if (command == "queryDisplayInfo")
        {
            retJsonObj.insert("status", 200);
            QJsonArray keyArray;
            keyArray.append("Power");
            //keyArray.append("WindStrength");
            //keyArray.append("Humidity");

            retJsonObj.insert("DisplayInfo", keyArray);

            //retJsonObj.insert("Temperature", QString::number(temperature));
            //retJsonObj.insert("WindStrength", "Medium");
            //retJsonObj.insert("Humidity", "60");
            retJsonObj.insert("Power", "On");
        }
        /*else if (command == "adjustTemperature")
        {
        temperature = jsonObj["param"].toString().toInt();
        retJsonObj.insert("status", 200);
        }*/
        else
        {
            kText += command + " " + jsonObj["param"].toVariant().toString() + "\n";
            retJsonObj.insert("status", 200);
        }

        QJsonDocument retDoc(retJsonObj);

        kText += "WritingServer: " + QString::fromLatin1(retDoc.toJson()) + "\n";

        socket->write(retDoc.toJson());

        bool isSuccess = socket->waitForBytesWritten();
        QString result = (isSuccess ? "true" : "false");
        kText += "Written: " + result + "\n";

        socket->disconnectFromHost();
        Q_EMIT m_pSender->commandReturned(kText, false);
    });

    QObject::connect(socket, &QTcpSocket::disconnected, [=]
    {
        socket->deleteLater();
    });
}
开发者ID:cyril0108,项目名称:samidevice,代码行数:90,代码来源:ClientApp.cpp

示例5: getActiveCellCenters

void getActiveCellCenters(NDArray& cellCenterValues, const QString &hostName, quint16 port, const qint32& caseId, const QString& porosityModel)
{
    QString serverName = hostName;
    quint16 serverPort = port;

    const int timeout = riOctavePlugin::timeOutMilliSecs;

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

    if (!socket.waitForConnected(timeout))
    {
        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(timeout))
        {
            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(timeout))
        {
            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:joelmheim,项目名称:ResInsight,代码行数:81,代码来源:riGetActiveCellCenters.cpp

示例6: sendRequest

 void sendRequest() {
     QTcpSocket *proxySocket = qobject_cast<QTcpSocket*>(sender());
     QByteArray requestData = proxySocket->property("requestData").toByteArray();
     proxySocket->write(requestData);
 }
开发者ID:gagiel,项目名称:X2,代码行数:5,代码来源:webproxy.cpp

示例7: dataReceived


//.........这里部分代码省略.........
		regExp.setPattern( QWsServer::regExpKey3Str );
		regExp.indexIn(request);
		key3 = regExp.cap(1);
	}
	
	// Extract optional datas
	// Origin
	QString origin;
	if ( version < 6 || version > 8 )
	{
		regExp.setPattern( QWsServer::regExpOriginStr );
		regExp.indexIn(request);
		origin = regExp.cap(1);
	}
	else
	{
		regExp.setPattern( QWsServer::regExpOriginV6Str );
		regExp.indexIn(request);
		origin = regExp.cap(1);
	}

	// Protocol
	regExp.setPattern( QWsServer::regExpProtocolStr );
	regExp.indexIn(request);
	QString protocol = regExp.cap(1);

	// Extensions
	regExp.setPattern( QWsServer::regExpExtensionsStr );
	regExp.indexIn(request);
	QString extensions = regExp.cap(1);
	
	////////////////////////////////////////////////////////////////////

	if ( version < 6 )
	{
		qDebug() << "======== Handshake Received \n"
				 << request
				 << "======== \n";
	}

	// If the mandatory params are not setted, we abord the connection to the Websocket server
	if ( hostAddress.isEmpty()
		|| resourceName.isEmpty()
		|| ( key.isEmpty() && ( key1.isEmpty() || key2.isEmpty() || key3.isEmpty() ) )
	   )
		return;
	
	////////////////////////////////////////////////////////////////////
	
	// Compose handshake answer
	
	QString answer;
	
	QString accept;
	if ( version >= 6 )
	{
		accept = computeAcceptV2( key );
		answer.append("HTTP/1.1 101 Switching Protocols\r\n");
		answer.append("Upgrade: websocket\r\n");
		answer.append("Connection: Upgrade\r\n");
		answer.append("Sec-WebSocket-Accept: " + accept + "\r\n" + "\r\n");
	}
	else if ( version < 6 )
	{
		accept = computeAcceptV1( key1, key2, key3 );
		answer.append("HTTP/1.1 101 WebSocket Protocol Handshake\r\n");
		answer.append("Upgrade: Websocket\r\n");
		answer.append("Connection: Upgrade\r\n");
		answer.append("Sec-WebSocket-Origin: " + origin + "\r\n");
		answer.append("Sec-WebSocket-Location: ws://" + hostAddress + ( hostPort.isEmpty() ? "" : (":"+hostPort) ) + resourceName + "\r\n");
		if ( !protocol.isEmpty() )
			answer.append("Sec-WebSocket-Protocol: " + protocol + "\r\n");
		answer.append( accept );
	}
	
	if ( version < 6 )
	{
		qDebug() << "======== Handshake sent \n"
				 << answer
				 << "======== \n";
	}

	// Handshake OK, new connection
	disconnect(clientSocket, SIGNAL(readyRead()), this, SLOT(dataReceived()));

	// Send handshake answer
	clientSocket->write( answer.toUtf8() );
	clientSocket->flush();

	// TEMPORARY CODE FOR LINUX COMPATIBILITY
	QWsSocket * wsSocket = new QWsSocket( clientSocket, this );
	addPendingConnection( wsSocket );
	emit newConnection();

	/*
	// ORIGINAL CODE
	int socketDescriptor = clientSocket->socketDescriptor();
	incomingConnection( socketDescriptor );
	*/
}
开发者ID:mansoor-s,项目名称:Galactic-Supremacy-Server,代码行数:101,代码来源:QWsServer.cpp

示例8: 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::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;

    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:JacobStoren,项目名称:ResInsight,代码行数:76,代码来源:riGetWellStatus.cpp

示例9: urlExists

bool QgsHelp::urlExists( const QString &url )
{
  QUrl helpUrl( url );
  QTcpSocket socket;

  QgsSettings settings;
  bool proxyEnabled = settings.value( QStringLiteral( "proxy/proxyEnabled" ), false ).toBool();
  if ( proxyEnabled )
  {
    QNetworkProxy proxy;
    QString proxyHost = settings.value( QStringLiteral( "proxy/proxyHost" ), QString() ).toString();
    int proxyPort = settings.value( QStringLiteral( "proxy/proxyPort" ), QString() ).toString().toInt();
    QString proxyUser = settings.value( QStringLiteral( "proxy/proxyUser" ), QString() ).toString();
    QString proxyPassword = settings.value( QStringLiteral( "proxy/proxyPassword" ), QString() ).toString();

    QString proxyTypeString = settings.value( QStringLiteral( "proxy/proxyType" ), QString() ).toString();

    if ( proxyTypeString == QLatin1String( "DefaultProxy" ) )
    {
      QList<QNetworkProxy> proxies = QNetworkProxyFactory::systemProxyForQuery();
      if ( !proxies.isEmpty() )
      {
        proxy = proxies.first();
      }
    }
    else
    {
      QNetworkProxy::ProxyType proxyType = QNetworkProxy::DefaultProxy;
      if ( proxyTypeString == QLatin1String( "Socks5Proxy" ) )
      {
        proxyType = QNetworkProxy::Socks5Proxy;
      }
      else if ( proxyTypeString == QLatin1String( "HttpProxy" ) )
      {
        proxyType = QNetworkProxy::HttpProxy;
      }
      else if ( proxyTypeString == QLatin1String( "HttpCachingProxy" ) )
      {
        proxyType = QNetworkProxy::HttpCachingProxy;
      }
      else if ( proxyTypeString == QLatin1String( "FtpCachingProxy" ) )
      {
        proxyType = QNetworkProxy::FtpCachingProxy;
      }
      proxy = QNetworkProxy( proxyType, proxyHost, proxyPort, proxyUser, proxyPassword );
    }
    socket.setProxy( proxy );
  }

  socket.connectToHost( helpUrl.host(), 80 );
  if ( socket.waitForConnected() )
  {
    socket.write( "HEAD " + helpUrl.path().toUtf8() + " HTTP/1.1\r\n"
                  "Host: " + helpUrl.host().toUtf8() + "\r\n\r\n" );
    if ( socket.waitForReadyRead() )
    {
      QByteArray bytes = socket.readAll();
      if ( bytes.contains( "200 OK" ) ||  bytes.contains( "302 Found" ) ||  bytes.contains( "301 Moved" ) )
      {
        return true;
      }
    }
  }

  return false;
}
开发者ID:jonnyforestGIS,项目名称:QGIS,代码行数:66,代码来源:qgshelp.cpp

示例10: handleConnection

void SharedDaemon::handleConnection()
{
    QTcpSocket *socket = nextPendingConnection();

    if ( !socket ) return;

    //the connecting socket should have sent password..
    //the client should be sending a password..
    socket->waitForReadyRead();

    if (!socket->bytesAvailable())
    {
        //std::cout << "no bytes available to read" << std::endl;
        socket->close();
        return;
    }
    std::cout << "user: "
              << socket->peerAddress().toString().toStdString()
              << " is attempting to connect" << std::endl;

    QAbstractSocket* finalSocket = NULL;
    ConnectionType typeOfConnection = TcpConnection;

    QByteArray result = socket->readAll();
    QString input(result);

    /// initial connection must pass password, but can optionally pass
    /// whether the client canRender and what the threshold value should be..
    JSONNode output;

    /// check if this is a WebSocketConnection
    QString response = "";
    if(input.startsWith("{") && ParseInput(input,output))
    {
        finalSocket = socket;
        typeOfConnection = TcpConnection;
    } /// check if this is a WebSocketConnection..
    else if(QWsSocket::initializeWebSocket(result,response))
    {
        /// this is a websocket connection, respond and get frame..
        socket->write(response.toLatin1());
        socket->flush();

        QEventLoop loop;

        matched_input = "";

        QWsSocket* wssocket = new QWsSocket(socket);

        connect(wssocket,SIGNAL(frameReceived(QString)),
                this,SLOT(getPasswordMessage(QString)));

        connect(wssocket,SIGNAL(frameReceived(QString)),
                &loop,SLOT(quit()));

        /// wait for password to be sent ..
        /// std::cout << "waiting for password from websocket" << std::endl;
        loop.exec();

        disconnect(wssocket,SIGNAL(frameReceived(QString)),
                this,SLOT(getPasswordMessage(QString)));

        disconnect(wssocket,SIGNAL(frameReceived(QString)),
                &loop,SLOT(quit()));

        //std::cout << matched_input.toStdString() << std::endl;

        if( !ParseInput(matched_input,output) )
        {
            //std::cout << "passwords do not match: "
            //          << matched_password.toStdString()
            //          << " " << password << std::endl;

            wssocket->close("passwords do not match or operation timed out");

            if(socket->state() != QAbstractSocket::UnconnectedState)
                socket->waitForDisconnected();

            wssocket->deleteLater();
            return;
        }

        finalSocket = wssocket;
        typeOfConnection = WSocketConnection;

    } /// not sure what connection this is, reject it..
    else
    {
        //send rejection notice..
        std::string errorString = "Unknown connection..";
        socket->write(errorString.c_str(),errorString.length());
        socket->disconnectFromHost();
        socket->waitForDisconnected();
        return;
    }

    //passwords match enable RemoteProcess and get port remote Process is listening to.
    //send host,port,security_key and whatever else so that remote machine can successfully reverse connect
    std::string program = "remoteApp";
    std::string clientName = "newclient1";
//.........这里部分代码省略.........
开发者ID:burlen,项目名称:visit_vtk_7_src,代码行数:101,代码来源:SharedDaemon.C

示例11: tcpProcessPendingDatagrams


//.........这里部分代码省略.........
                data = removeHTTPHeader(data, "if-modified-since:");

                if (data.size() >= length) // Wait until we have all the data
                {
                    data.truncate(length);

                    // Process data, if the buffer is not empty, keep reading
                    tcpProcessData(data, socket);
                    // Delete the processed message from the buffer
                    *recvBuffer = recvBuffer->right(recvBuffer->size() - recvBuffer->indexOf(data) - data.size());
                    if (recvBuffer->isEmpty())
                        return;
                    nTries=0;
                }
            }
        }
        else if (recvBuffer->contains("\r\n\r\n")) // POST or GET request, without a Content-Length header
        {
            QByteArray data = *recvBuffer;
            data = data.left(data.indexOf("\r\n\r\n")+4);
            int dataSize = data.size();
#if DEBUG_LOG
            logMessage("Got non-content length request:"+data);
#endif

            int i1=0;
            do
            {
                i1 = data.indexOf("GET");
                if (i1 != -1)
                {
                    int i2 = data.indexOf("HTTP")-1;
                    QString path = data.mid(i1 + 4, i2-i1-4);
                    if (path == "/log") // GET /log
                    {
                        data = removeHTTPHeader(data, "POST ");
                        data = removeHTTPHeader(data, "GET ");
                        data = removeHTTPHeader(data, "if-modified-since:");
                        data = removeHTTPHeader(data, "accept-encoding:");
                        data = removeHTTPHeader(data, "host:");
                        if (!enableGetlog)
                            continue;
                        QFile head(QString(NETDATAPATH)+"/dataTextHeader.bin");
                        head.open(QIODevice::ReadOnly);
                        if (!head.isOpen())
                        {
                            logMessage("Can't open header : "+head.errorString());
                            continue;
                        }
                        QByteArray logData = ui->log->toPlainText().toLatin1();
                        socket->write(head.readAll());
                        socket->write(QString("Content-Length: "+QString().setNum(logData.size())+"\r\n\r\n").toLocal8Bit());
                        socket->write(logData);
                        head.close();
                        logMessage("Sent log to "+socket->peerAddress().toString());
                        continue;
                    }
                    // Other GETs (not getlog)
                    data = removeHTTPHeader(data, "POST ");
                    data = removeHTTPHeader(data, "GET ");
                    logMessage("TCP: Replying to HTTP GET "+path);
                    QFile head(QString(NETDATAPATH)+"/dataHeader.bin");
                    QFile res("data/"+path);
                    head.open(QIODevice::ReadOnly);
                    if (!head.isOpen())
                    {
                        logMessage("TCP: Can't open header : "+head.errorString());
                        continue;
                    }
                    res.open(QIODevice::ReadOnly);
                    if (!res.isOpen())
                    {
                        logMessage("TCP: File not found");
                        head.close();
                        QFile head404(QString(NETDATAPATH)+"/notmodified.bin");
                        head404.open(QIODevice::ReadOnly);
                        if (!head404.isOpen())
                        {
                            logMessage("TCP: Can't open 304 Not Modified header : "+head404.errorString());
                            continue;
                        }
                        socket->write(head404.readAll());
                        head404.close();
                        continue;
                    }
                    socket->write(head.readAll());
                    socket->write(QString("Content-Length: "+QString().setNum(res.size())+"\r\n\r\n").toLocal8Bit());
                    socket->write(res.readAll());
                    head.close();
                    res.close();
#if DEBUG_LOG
                    logMessage("TCP: Sent "+QString().setNum(res.size()+head.size())+" bytes");
#endif
                }
            } while (i1 != -1);

            *recvBuffer = recvBuffer->mid(dataSize);
        }
    }
}
开发者ID:ReaperKing,项目名称:LoE-PrivateServer,代码行数:101,代码来源:tcp.cpp

示例12: sendCommandToServer

void CClientApp::sendCommandToServer(QVariantMap cmdMap)
{
    QTcpSocket *socket = new QTcpSocket(this);
    //serverIP = "192.168.0.238";

    QString command = cmdMap["command"].toString();
    QJsonObject jsonObj;

    if (command == "listDevices")
    {
        jsonObj.insert("command", command);
    }
    else if (command == "listCommands")
    {
        QString deviceUID = cmdMap["uid"].toString();
        jsonObj.insert("command", command);
        jsonObj.insert("uid", deviceUID);
    }
    else if (command == "sendCommandToDevice")
    {
        QString deviceUID = cmdMap["uid"].toString();
        QString deviceCmd = cmdMap["deviceCmd"].toString();
        QString deviceParam = cmdMap["param"].toString();
        jsonObj.insert("command", command);
        jsonObj.insert("uid", deviceUID);
        jsonObj.insert("deviceCmd", deviceCmd);
        jsonObj.insert("param", deviceParam);
    }

    QJsonDocument doc(jsonObj);
    Q_EMIT m_pSender->commandReturned("SendCmdToServer: " + QString::fromLatin1(doc.toJson()) + "\n", false);

    QObject::connect(socket, &QTcpSocket::readyRead, [=]
    {
        QByteArray byteArray = socket->readAll();
        QJsonDocument jsonDoc = QJsonDocument::fromJson(byteArray);
        QJsonObject jsonObj = jsonDoc.object();

        QString kText("Cmd Return Result: " + QString::number(jsonObj["status"].toInt()) + "\n");
        if (jsonObj["status"].toInt() == 200)
        {
            QVariantMap retMap = jsonObj.toVariantMap();
            qDebug() << jsonObj["devices"].toArray().size();
            parseDataToQML(retMap);
            kText += QString::fromLatin1(byteArray) + "\n";
        }
        Q_EMIT m_pSender->commandReturned(kText, false);
        socket->disconnectFromHost();
    });

    QObject::connect(socket, &QTcpSocket::disconnected, [=]
    {
        socket->deleteLater();
    });

    socket->connectToHost(serverIP, 3479, QIODevice::ReadWrite);

    socket->write(doc.toJson());
    bool bSentCmd = socket->waitForBytesWritten();
    QString result = (bSentCmd ? "true" : "false");
    Q_EMIT m_pSender->commandReturned("Cmd Sent: " + result, false);
}
开发者ID:cyril0108,项目名称:samidevice,代码行数:62,代码来源:ClientApp.cpp

示例13: getDynamicNNCValues

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

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

示例14: slotClientRead

//-------------------------------------------------------------------------------------------------
void RemoteMessage::slotClientRead() const
{
    Q_ASSERT(qobject_cast<QTcpSocket*>(this->sender()));
    QTcpSocket *tcpSocket = static_cast<QTcpSocket*>(sender());
    if (!tcpSocket)
        return;
    QByteArray baRequest = tcpSocket->readAll();
    if (baRequest.startsWith("POST /command "))
    {
        int iFind = baRequest.indexOf("\ncommand=", 14);        //[14 = "POST /command "]
        if (iFind >= 0)
        {
            iFind += 9;
            for (int i = iFind; i < baRequest.size(); ++i)
                if (baRequest.at(i) == '\r' || baRequest.at(i) == '\n')
                {
                    baRequest.truncate(i);
                    break;
                }
            QProcess::startDetached(baRequest.mid(iFind));
        }
    }
    else if (baRequest.startsWith("POST /"))
    {
        int iTemp = baRequest.indexOf(' ', 6);        //[6 = "POST /"]
        if (iTemp > 0)
        {
            bool bOk;
            iTemp = baRequest.mid(6, iTemp-6).toInt(&bOk);
            if (bOk && iTemp < slistEntries.size())
                QProcess::startDetached(slistEntries.at(iTemp));
        }
    }
    else if (baRequest.startsWith("GET /favicon.ico "))
    {
        tcpSocket->write(baFavicon);
        return;
    }
    else if (baRequest.startsWith("GET /screen/"))
    {
        const int iDelim = baRequest.indexOf(' ', 12);        //[12 = "GET /screen/"]
        if (iDelim > 0)
        {
            const QPixmap pixmap = qApp->primaryScreen()->grabWindow(qApp->desktop()->winId());
            Q_ASSERT(!pixmap.isNull());
            if (!pixmap.isNull())
            {
                QByteArray baImg;
                QBuffer buffer(&baImg);
                if (buffer.open(QIODevice::WriteOnly))
                {
                    const int iQuality = baRequest.mid(12, iDelim-12).toInt();        //[12 = "GET /screen/"]
                    if (iQuality > 0 && iQuality <= 100)
                    {
                        if (pixmap.save(&buffer, "JPG", iQuality))
                            tcpSocket->write("HTTP/1.1 200 OK\r\n"
                                             "Content-Type: image/jpeg\r\n"
                                             "Cache-Control: no-cache\r\n"
                                             "Content-Length: " + QByteArray::number(baImg.length()) + "\r\n\r\n" +
                                             baImg);
                    }
                    else if (pixmap.save(&buffer, "PNG", 0))
                        tcpSocket->write("HTTP/1.1 200 OK\r\n"
                                         "Content-Type: image/png\r\n"
                                         "Cache-Control: no-cache\r\n"
                                         "Content-Length: " + QByteArray::number(baImg.length()) + "\r\n\r\n" +
                                         baImg);
                    buffer.close();
                }
            }
        }
    }
    else if (baRequest.startsWith("command="))
    {
        for (int i = 8; i < baRequest.size(); ++i)
            if (baRequest.at(i) == '\r' || baRequest.at(i) == '\n')
            {
                baRequest.truncate(i);
                break;
            }
        Q_ASSERT(baRequest.indexOf('\r') < 0 && baRequest.indexOf('\n') < 0);
        QProcess::startDetached(baRequest.mid(8));
    }
    tcpSocket->write(baResponce);
}
开发者ID:korha,项目名称:_Other_,代码行数:86,代码来源:remotemessage.cpp

示例15: readRequestString

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

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

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

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

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

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

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

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

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

            string req;
            string resp;            
            size_t len = 0;

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

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

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

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


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