本文整理汇总了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;
}
}
}
示例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;
}
示例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();
}
示例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);
}
}
}
示例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!");
}
示例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;
}
示例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;
}
}
}
示例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;
}
示例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
}
示例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();
}
示例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;
}
}
示例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;
}
示例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");
}
示例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);
}
}
示例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;
}