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


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

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


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

示例1: readBody

void HttpRequest::readBody(QTcpSocket& socket) {
      Q_ASSERT(expectedBodySize != 0);
      if (boundary.isEmpty()) {
            // normal body, no multipart
#ifdef SUPERVERBOSE
            qDebug("HttpRequest: receive body");
#endif
            int toRead = expectedBodySize - bodyData.size();
            QByteArray newData = socket.read(toRead);
            currentSize += newData.size();
            bodyData.append(newData);
            if (bodyData.size() >= expectedBodySize) {
                  status = complete;
                  }
            }
      else {
            // multipart body, store into temp file
#ifdef SUPERVERBOSE
            qDebug("HttpRequest: receiving multipart body");
#endif
            if (!tempFile.isOpen()) {
                  tempFile.open();
                  }
            // Transfer data in 64kb blocks
            int fileSize = tempFile.size();
            int toRead = expectedBodySize - fileSize;
            if (toRead > 65536) {
                  toRead = 65536;
                  }
            fileSize += tempFile.write(socket.read(toRead));
            if (fileSize >= maxMultiPartSize) {
                  qWarning("HttpRequest: received too many multipart bytes");
                  status = abort;
                  }
            else if (fileSize >= expectedBodySize) {
#ifdef SUPERVERBOSE
                  qDebug("HttpRequest: received whole multipart body");
#endif
                  tempFile.flush();
                  if (tempFile.error()) {
                        qCritical("HttpRequest: Error writing temp file for multipart body");
                        }
                  parseMultiPartFile();
                  tempFile.close();
                  status = complete;
                  }
            }
      }
开发者ID:UIKit0,项目名称:mscoreserver,代码行数:48,代码来源:httprequest.cpp

示例2: OnClientData

void TcpServer::OnClientData()
{
	QTcpSocket* connection = qobject_cast<QTcpSocket*>(sender());
	quint64 bufferSize = 2048;
	char buffer[bufferSize];
	quint64 dataRead = 0;

	dataRead = connection->read(buffer, bufferSize);
	buffer[dataRead] = 0;

	//qDebug() << "[WEB] Incoming data[" << dataRead << "]: " << buffer;

	QString value;

	//Check if it's a Flash policy request, only the first time
	//if (this->justConnected == true) {
		value = buffer;
		if (value.contains("<policy-file-request/>")) {
			connection->write(XML_CROSS_DOMAIN);
			qDebug() << "[TcpServer::OnClientData] Sent xml cross domain file";
			//this->justConnected = false;
			return;
		}
		else if ( value.contains("HTTP") ) {	//then its HTTP request

			QString response;

			//Check the data and create response
			DataHandler(value, response);
			HttpResponse httpHeader(response);

			connection->write( httpHeader.GetHeader() );
			connection->write( response.toUtf8().constData() );

			connection->close();
		}
	//}
	//Other requests that are not http requests or posts
	// This may be deleted
	//else {
		else if (value == "CORE") {
			XmlParser xml(buffer, dataRead);
			int action = CEMI_ACTION_WRITE;
			int groupAddr = 0;

			xml.GetValue("cmd", value);
			if (value == "write") action = CEMI_ACTION_WRITE;
			else if (value == "read") action = CEMI_ACTION_READ;

			xml.GetValue("groupAddr", value);
			groupAddr = Common::GroupAddrToInt(value);
			//qDebug() << "groupAddr: " << value;

			xml.GetValue("value", value);

			emit TcpServerData((int)action, groupAddr, value);
		}
	//}
	//this->justConnected = false;
}
开发者ID:SkySparky,项目名称:Qt-KNX-Server,代码行数:60,代码来源:tcpServer.cpp

示例3: run

void ThreadJoueurs::run()
{
    QTcpSocket unSocket;


    unSocket.setSocketDescriptor(m_socketDescriptor);
    if(unSocket.waitForConnected(1000))
    {
        while(unSocket.ConnectedState)         //.waitForReadyRead(1000))
        {
            baRXInfos=unSocket.read(unSocket.bytesAvailable());
            if(baRXInfos.left(1) == "&")    //code de connection des joueurs
            {
                unSocket.write(baTXInfos.append(cNoJ));     //assignation du numero
                baTXInfos = TXInfosToJoueurs(m_tNouvellePartie,9);  // trame de debut de partie (= NouvellePartie)
            }
            else
            {
                RXInfosFmJoueurs(baRXInfos);                //recoit {'#', JnX, JnY}
                baTXInfos = TXInfosToJoueurs(m_txInfos,9);  //repond trame {code, balle X, balle Y, J1X, J1Y, J2X, J2Y, ScoreA, ScoreB}
            }                                               // code = '#' (normale), '$' (gagnant), '%' (Nouvelle Balle)
            unSocket.write(baTXInfos);
            unSocket.waitForBytesWritten(10);
        }
    }
    unSocket.disconnectFromHost();
    unSocket.close();

}
开发者ID:Sassinak,项目名称:cll12-Pong,代码行数:29,代码来源:threadjoueurs.cpp

示例4: onTcpReadyRead

void Tunneld::onTcpReadyRead()
{
    QTcpSocket *sock = (QTcpSocket*)sender();
    ToxTunChannel *chan = this->m_sock_chans[sock];

    if (chan->m_enpeer->state == ENET_PEER_STATE_CONNECTED) {
        while (sock->bytesAvailable() > 0) {
            // QByteArray ba = sock->readAll();
            QByteArray ba = sock->read(567);
            if (ba.length() >= 1371) {
                qDebug()<<"too long data packet.";
            }
        
            ENetPacket *packet = enet_packet_create(ba.data(), ba.length(), ENET_PACKET_FLAG_RELIABLE);

            // enet_packet_resize(packet, 13);
            // strcpy((char*)&packet->data[9], "foo");
    
            uint8_t chanid = 0;
            ENetPeer *enpeer = chan->m_enpeer;
            // enet_peer_send(enpeer, chanid, packet);
            m_enpoll->sendPacket(enpeer, chanid, packet);
        }
    }

}
开发者ID:kitech,项目名称:toxsh,代码行数:26,代码来源:tunneld.cpp

示例5: run

//worker in thread
void CommThrd::run()
{
    QTcpSocket qtcpSelfClient;
    QHostAddress qhostLocal("127.0.0.1");
    qtcpSelfClient.connectToHost(qhostLocal, 35791);
    //connect successfully
    if(qtcpSelfClient.waitForConnected())
    {
        //send request message !!!need to be modified
        //replace \n to \r\n
        QRegExp qreTemp("\\n");
        mpqstrRequ->replace(qreTemp, "\r\n");
        QByteArray qbyaRequ = mpqstrRequ->toAscii();
        int i=qtcpSelfClient.write(qbyaRequ);
        if(i==-1)
            return;
            //QMessageBox::information(this, "Composer Error", "Can't send request to localhost!");
        qtcpSelfClient.waitForBytesWritten();
        //read response
        int iAvail = 0;
        QByteArray qbyaResp;
        bool bReady = qtcpSelfClient.waitForReadyRead(30000);
        iAvail = qtcpSelfClient.bytesAvailable();
        qbyaResp = qtcpSelfClient.read(iAvail);
        delete mpqstrRequ;
        mpqstrRequ = new QString(qbyaResp);
        //post message to UI
        ERespAvail *pclsEvnt = new ERespAvail() ;
        qApp->postEvent((QObject*)(pwdMainWin->pwinComposer), pclsEvnt);
    }
        //QMessageBox::information(this, "Composer Error", "Can't connect to localhost!");
}
开发者ID:byron90,项目名称:webdebug,代码行数:33,代码来源:composer.cpp

示例6: onConnect

void GameServer::onConnect()
{
    qDebug() << "CONNECTED";

    QTcpSocket* socket = _server->nextPendingConnection();
    socket->waitForReadyRead();

    qDebug() << socket->bytesAvailable();

    const int MaxLength = 1024;
    char buffer[MaxLength + 1];

    qint64 byteCount = socket->read(buffer, MaxLength);
    buffer[byteCount] = 0;

    qDebug() << buffer;

    const char* response =
        "HTTP/1.1 200 OK\r\n"
        "Connection: close\r\n"
        "Content-Type: text/html; charset=UTF-8\r\n"
        "\r\n"
        "<html><head><title>XPG Server</title></head>"
        "<body><p>Hello, World! Text is da bomb.</p></body>"
        "</html>"
        ;

    qDebug() << socket->write(response);

    socket->waitForBytesWritten();

    socket->close();
    delete socket;
}
开发者ID:TheBuzzSaw,项目名称:Droideka,代码行数:34,代码来源:GameServer.cpp

示例7: handleClientRead

void CDaemon::handleClientRead()
{
	QTcpSocket * socket = qobject_cast<QTcpSocket *>(sender());

	while(socket->bytesAvailable() > 8)
	{
		QDataStream stream(socket);
		quint64 size;

		stream >> size;
		if(socket->bytesAvailable() >= size)
		{
			QByteArray buffer(socket->read(size));
			QDataStream bStream(buffer);
			quint8 opcode;

			bStream >> opcode;
			switch(opcode)
			{
			case OPCODE_ADD:
				handleAdd(bStream); break;
			case OPCODE_REMOVE:
				handleRemove(bStream); break;
			case OPCODE_START:
				handleStart(bStream); break;
			case OPCODE_STOP:
				handleAbort(bStream); break;
			case OPCODE_QUEUE:
				handleQueue(bStream); break;
			default:
				qWarning() << "Unhandled packet:" << quint32(opcode); break;
			}
		}
	}
开发者ID:vojtad,项目名称:uloz-to-daemon,代码行数:34,代码来源:CDaemon_communication.cpp

示例8: send

bool Http::send(QString host, int port, QByteArray data, QByteArray &result, int timeout)
{
    QByteArray response;
    QTcpSocket socket;
    int numRead = 0;
    int numReadTotal = 0;
    char buffer[50];

    socket.connectToHost(QHostAddress(host),port);
    if (!socket.waitForConnected(timeout)) {
        return false;
    }

    socket.write(data);
    if (!socket.waitForBytesWritten(timeout))
    {
        return false;
    }

    forever {
        numRead  = socket.read(buffer, 50);
        numReadTotal += numRead;
        response.append(buffer,numRead);
        if (numRead == 0 && !socket.waitForReadyRead(timeout))
            break;
    }
    socket.disconnectFromHost();

    int header = response.indexOf("\r\n\r\n");
    if (header != -1) {
        result = response.mid(header+4);
    }
    return true;
}
开发者ID:chenbaohai,项目名称:multiScreenClient,代码行数:34,代码来源:http.cpp

示例9: getSensorTemperature

int MainWindow::getSensorTemperature(){
   // Get the server address and port from the settings dialog box
   int serverPort = this->dialog->getServerPort();  // get from the dialog box
   quint32 serverAddr = this->dialog->getIPAddress();   // from the dialog box
   QTcpSocket *tcpSocket = new QTcpSocket(this);    // create socket
   tcpSocket->connectToHost(QHostAddress(serverAddr), serverPort); // connect
   if(!tcpSocket->waitForConnected(1000)){    //wait up to 1s for a connection
      statusBar()->showMessage("Failed to connect to server...");
      return 1;
   }
   // Send the message "getTemperature" to the server
   tcpSocket->write("getTemperature");
   if(!tcpSocket->waitForReadyRead(1000)){    // wait up to 1s for the server
      statusBar()->showMessage("Server did not respond...");
      return 1;
   }
   // If the server has sent bytes back to the client
   if(tcpSocket->bytesAvailable()>0){
      int size = tcpSocket->bytesAvailable(); // how many bytes are ready?
      char data[20];                          // upper limit of 20 chars
      tcpSocket->read(&data[0],(qint64)size); // read the number of bytes rec.
      data[size]='\0';                        // termintate the string
      this->curTemperature = atof(data);      // string -> float conversion
      cout << "Received the data [" << this->curTemperature << "]" << endl;
   }
   else{
      statusBar()->showMessage("No data available...");
   }
   return 0;    // the on_updateTemperature() slot will update the display
}
开发者ID:19Dan01,项目名称:exploringBB,代码行数:30,代码来源:mainwindow.cpp

示例10: TcpReadFromProxy

  void ExitTunnel::TcpReadFromProxy()
  {
    if(!_running) {
      qDebug("SOCKS read but not running");
      return;
    }

    QTcpSocket* socket = qobject_cast<QTcpSocket*>(sender());
    if(!socket) {
      qWarning("SOCKS Illegal call to ReadFromClient()");
      return;
    }

    if(!CheckSession()) {
      qDebug("SOCKS read but no session");
      return;
    }
  
    do {
      QByteArray data = socket->read(64000);
      qDebug() << "SOCKS Read" << data.count() << "bytes from proxy socket";
      TcpResponsePacket resp(_table.IdForConnection(socket), data);
      //GetSession()->Send(resp.ToByteArray());
      //qDebug() << "SOCKS " << data;
      SendReply(resp.ToByteArray());
    } while(socket->bytesAvailable());

    qDebug() << "MEM active" << _table.Count();
  }
开发者ID:ranzhao1,项目名称:Dissent-1,代码行数:29,代码来源:ExitTunnel.cpp

示例11: run

/*!
 * @brief
 * this thread will read text from the Network
 * and create events to write that text.
 */
void NetHandler::run()
{
	s = new QTcpServer();
	if (!s->listen(QHostAddress(addr), port))
	{
		qDebug() << "listening on " << addr.toString() << ":" << port << " failed";
		delete s;
		return;
	}
	char b[1024]; // buffer
	int n;        // bytes read
	bool state;
	QTcpSocket *socket = NULL;
	while (1)
	{
		state = s->waitForNewConnection(1000);
		// check if we should stop the loop
		if (sd.terminating)
		{
			s->close();
			delete s;
			return;
		}
		if (!state)
			continue;
		
		socket = s->nextPendingConnection();
		qDebug() << "Yay! Someone connected at " << QDateTime::currentDateTime();
		
		while(1)
		{
			state = socket->waitForReadyRead(1000);
			// check if we should stop the loop
			if (sd.terminating)
			{
				s->close();
				delete socket;
				delete s;
				return;
			}
			if (!state)
				if (socket->state() == QAbstractSocket::UnconnectedState)
				{
					qDebug() << "Nay! Someone disconnected at " << QDateTime::currentDateTime();
					break;
				}
				else
					continue;
			
			while (socket->bytesAvailable())
			{
				n = socket->read(b, 1016);
				actOnData(b, n);
			}	
		}
		delete socket;
	}
}
开发者ID:kermitfrog,项目名称:inputmangler,代码行数:63,代码来源:nethandler.cpp

示例12: read

static bool read(QTcpSocket &sock, char *ptr, qint64 sz)
{
    do {
        qint64 readBytes = sock.read(ptr, sz);
        ptr += readBytes;
        sz -= readBytes;
    } while(sz && sock.waitForReadyRead());
    return sz == 0;
}
开发者ID:Dhanasekahar,项目名称:apitrace,代码行数:9,代码来源:androidretracer.cpp

示例13: run

void TcpEchoServerSession::run()
{
    LOG_INFO("Beginning of TcpEchoServerSession::run");

    QTcpSocket socket;
    if( !socket.setSocketDescriptor(m_socketDescriptor))
    {
        LOG_ERROR("Cannot set socket descriptor");
    }

    while( true )
    {
        // Receive request
        qint16 fillSize;
        qint16 echoSize;

        while( socket.bytesAvailable() < 4 )
        {
            if( !socket.waitForReadyRead(-1)) // Intervals may vary
            {
                break;
            }
        }
        if( socket.state() == QAbstractSocket::UnconnectedState )
        {
            break; // Connection closed by client
        }

        QDataStream in(&socket);
        in >> fillSize >> echoSize;
        
        // Receive filled bytes in the request
        while( socket.bytesAvailable() < fillSize )
        {
            if( !socket.waitForReadyRead(3 * 1000))
            {
                LOG_INFO("TcpEcho session timed out");
                return;
            }
        }
        socket.read(fillSize);
        
        // Send data
        QByteArray block(echoSize, 0);
        socket.write(block);
        socket.waitForBytesWritten(-1);

        if( socket.state() == QAbstractSocket::UnconnectedState )
        {
            break;
        }
        //LOG_DEBUG("TcpEchoSession sent an echo of %d bytes", (int)echoSize);
    }
    
    socket.close();
    LOG_INFO("End of TcpEchoServerSession::run");
}
开发者ID:windy32,项目名称:algts,代码行数:57,代码来源:tcp-echo-server.cpp

示例14: onSocketReadyRead

void KCToolServer::onSocketReadyRead()
{
	QTcpSocket *socket = qobject_cast<QTcpSocket*>(QObject::sender());

	// Parse the first line
	if(!socket->property("firstLineRead").toBool())
	{
		QString line(socket->readLine());
		int sepPos1(line.indexOf(" "));
		int sepPos2(line.indexOf(" ", sepPos1+1));
		QString method(line.left(sepPos1));
		QString path(line.mid(sepPos1+1, sepPos2 - sepPos1 - 1));
		socket->setProperty("method", method);
		socket->setProperty("path", path);
		socket->setProperty("firstLineRead", true);
	}

	// Parse Headers!
	if(!socket->property("headerRead").toBool()) {
		QVariantMap headers(socket->property("headers").toMap());

		while(socket->canReadLine()) {
			QString line = QString(socket->readLine()).trimmed();

			// The header section is terminated by an empty line
			if(line == "") {
				socket->setProperty("headerRead", true);
				break;
			}

			// Split it up
			int sepPos(line.indexOf(":"));
			QString key(line.left(sepPos).trimmed());
			QString val(line.mid(sepPos+1).trimmed());
			headers.insertMulti(key, val);
		}

		socket->setProperty("headers", headers);
	}

	qint64 contentLength = socket->property("headers").toMap().value("Content-Length").toLongLong();
	// Read the body into a buffer
	if(socket->bytesAvailable()) {
		QByteArray buffer(socket->property("buffer").toByteArray());
		qint64 toRead = contentLength - buffer.size();
		buffer.append(socket->read(toRead));
		socket->setProperty("buffer", buffer);
		socket->setProperty("toRead", contentLength - buffer.size());

		// If we have a Content-Length (toLong() fails with 0)
		if(contentLength > 0 && buffer.size() >= contentLength)
			this->handleRequest(socket);
	} else if(contentLength == -1 || contentLength == 0) {
		this->handleRequest(socket);
	}
}
开发者ID:ElliotZ,项目名称:KanColleTool,代码行数:56,代码来源:KCToolServer.cpp

示例15: readRequest

void Server::readRequest(){
    cout<<"new request"<<endl;
    QTcpSocket* client = (QTcpSocket*)sender();
    char* buffer = new char[client->bytesAvailable()];
  	client->read(buffer, client->bytesAvailable());
    cout <<"request was: "<<buffer<< endl;
    rh = new RequestHandler(buffer);
    rh->respond(client);
    delete rh;
    delete buffer;
}
开发者ID:AnvarGazizov,项目名称:COMP3004,代码行数:11,代码来源:Server.cpp


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