1
votes

This slot has to put messages into buffer of a socket, but signal readyRead() is not send. I found out that size of written data the same as array size but method bytesAvailable() always returns zero. Can not understand why it happens

Code:

void Client::slotMessageSend()
{
  QByteArray array;
  QDataStream str(&array, QIODevice::WriteOnly);
  str.setVersion(QDataStream::Qt_4_5);
  str << quint16(0) << QTime::currentTime() << ui->textMessage->toPlainText() ;

  str.device()->seek(0);
  str << quint16(array.size() - sizeof(quint16));
  cout << pClientSocket->write(array) << endl;
  cout << array.size()<< "   " << pClientSocket->bytesAvailable() << endl;

  ui->textMessage->setPlainText("");

}

1
Have you seen the Qt socket examples? It looks a little weird, what are you trying to do with that code? Usually you write to a socket and the receiver (i.e. a socket server) may send something back and then you can read the data and have some bytes available and bytesAvailable() will be >0.xander
I want to write data to a socket and read this data at my client and my serverVitya Miroshnychenko

1 Answers

0
votes

QTcpSocket::readyRead will be emitted when new data is ready for read. In that case, QTcpSocket::bytesAvailable returns the size of data that is available. It will always return 0 if no data had been sent to that socket.

Calling that function mostly only make sense in the slot that reacts on readyRead signal.

If your intention is to read the data that had been sent back after you wrote to the socket - because the client side always responds to a write - it could be either that there is no data available yet, or that the other side never sent any data back.

You could try following:

pClientSocket->write(...)
if (pClientSocket->waitForReadyRead(...)) {
    // yes there is data available
    // pClientSocket->bytesAvailable() > 0
}

Example how to do it the better way:

Client::Client() {
    connect(pClientSocket, &QTcpSocket::readyRead, this, &Client::HandleRead);
    connect(pClientSocket, &QTcpSocket::bytesWritten, this, &Client::HandleWrite);
}

Client::SendSomeData(const QByteArray& Data) {
    pClientSocket->write(Data);
}

Client::HandleWrite(qint64 Size) {
    // Size bytes are written to socket buffer...
}

Client::HandleRead() {
    // pClientSocket->bytesAvailable() are available in socket buffer...
}