3
votes

I am using a QLocalSocket which is derived from QIODevice. The documentation for QIODevice::write says

Writes at most maxSize bytes of data from data to the device. Returns the number of bytes that were actually written, or -1 if an error occurred.

I am confused in what circumstances the function writes less than maxSize bytes of data and the documentation doesn't seem to tell me that. I could loop like this

for(int written = 0; written != len;) {
  int writtenNow = sock->write(data + written, len - written);
  if(writtenNow != -1) {
    written += writtenNow;
  } else {
    // oops, call cops!
  }
}

But what to do when it doesn't write all the data? Should I call waitForBytesWritten? According to the docs of QLocalSocket, this shouldn't bee needed

Though QLocalSocket is designed for use with an event loop, it's possible to use it without one. In that case, you must use waitForConnected(), waitForReadyRead(), waitForBytesWritten(), and waitForDisconnected() which blocks until the operation is complete or the timeout expires.

Hence I am deeply confused. Can anyone please shed some light on this?

1

1 Answers

0
votes

I solve this kind problems like this, it runs write method in the separate thread and main thread doesn't blocking

...
QtConcurrent::run(this, &MyClass::writeAsync, sock, data);
...

void MyClass::writeAsync(QLocalSocket socket, QByteArray data) {
    socket->write(data);
}