example c++ qt qtcpsocket

c++ - qtcpsocket server client example



Lea desde QTcpSocket usando QDataStream (3)

Necesito enviar datos binarios a través de un QTcpSocket . Estaba pensando en usar QDataStream , pero me encontré con un problema: falla silenciosamente si no se han QDataStream datos en el momento en que trato de leer.

Por ejemplo, si tengo este código:

QString str; stream >> str;

Fallará silenciosamente si no hay datos actualmente en el socket. ¿Hay alguna manera de decirle que bloquee?


El problema es un poco más serio. Socket puede recibir datos en fragmentos, por lo que incluso si espera waitForReadyRead , puede fallar debido a que no hay datos suficientes para leer inmediatamente algún objeto.
Para resolver este problema, debe enviar un tamaño de datos primero y luego datos reales. Enviar código:

QByteArray block; QDataStream sendStream(&block, QIODevice::ReadWrite); sendStream << quint16(0) << str; sendStream.device()->seek(0); sendStream << (quint16)(block.size() - sizeof(quint16)); tcpSocket->write(block);

En el receptor, debe esperar hasta que el tamaño de los datos disponibles cumpla con los requisitos. El código del receptor se parece más o menos así:

void SomeClass::slotReadClient() { // slot connected to readyRead signal of QTcpSocket QTcpSocket *tcpSocket = (QTcpSocket*)sender(); QDataStream clientReadStream(tcpSocket); while(true) { if (!next_block_size) { if (tcpSocket->bytesAvailable() < sizeof(quint16)) { // are size data available break; } clientReadStream >> next_block_size; } if (tcpSocket->bytesAvailable() < next_block_size) { break; } QString str; clientReadStream >> str; next_block_size = 0; } } pequeña actualización, según la documentación , es posible leer QString sin agregar información de tamaño adicional, ya que QString transferido a QDataStream contiene información de tamaño. El tamaño se puede verificar así:

void SomeClass::slotReadClient() { // slot connected to readyRead signal of QTcpSocket QTcpSocket *tcpSocket = (QTcpSocket*)sender(); while(true) { if (tcpSocket->bytesAvailable() < 4) { break; } char buffer[4] quint32 peekedSize; tcpSocket->peek(buffer, 4); peekedSize = qFromBigEndian<quint32>(buffer); // default endian in QDataStream if (peekedSize==0xffffffffu) // null string peekedSize = 0; peekedSize += 4; if (tcpSocket->bytesAvailable() < peekedSize) { break; } // here all required for QString data are available QString str; QDataStream(tcpSocket) >> str; emit stringHasBeenRead(str); } }


Puede llamar a la función QTCPSocket :: waitForReadyRead, que bloqueará hasta que los datos estén disponibles, o se conectará a la señal de readyRead () y cuando se llame a su ranura, luego leerá de la transmisión.


Repasé el código de la idea de @ Marek y creé 2 clases: BlockReader y BlockWriter:

Uso de muestra:

// Write block to the socket. BlockWriter(socket).stream() << QDir("C:/Windows").entryList() << QString("Hello World!"); .... // Now read the block from the socket. QStringList infoList; QString s; BlockReader(socket).stream() >> infoList >> s; qDebug() << infoList << s;

BlockReader:

class BlockReader { public: BlockReader(QIODevice *io) { buffer.open(QIODevice::ReadWrite); _stream.setVersion(QDataStream::Qt_4_8); _stream.setDevice(&buffer); quint64 blockSize; // Read the size. readMax(io, sizeof(blockSize)); buffer.seek(0); _stream >> blockSize; // Read the rest of the data. readMax(io, blockSize); buffer.seek(sizeof(blockSize)); } QDataStream& stream() { return _stream; } private: // Blocking reads data from socket until buffer size becomes exactly n. No // additional data is read from the socket. void readMax(QIODevice *io, int n) { while (buffer.size() < n) { if (!io->bytesAvailable()) { io->waitForReadyRead(30000); } buffer.write(io->read(n - buffer.size())); } } QBuffer buffer; QDataStream _stream; };

BlockWriter:

class BlockWriter { public: BlockWriter(QIODevice *io) { buffer.open(QIODevice::WriteOnly); this->io = io; _stream.setVersion(QDataStream::Qt_4_8); _stream.setDevice(&buffer); // Placeholder for the size. We will get the value // at the end. _stream << quint64(0); } ~BlockWriter() { // Write the real size. _stream.device()->seek(0); _stream << (quint64) buffer.size(); // Flush to the device. io->write(buffer.buffer()); } QDataStream &stream() { return _stream; } private: QBuffer buffer; QDataStream _stream; QIODevice *io; };