Behavior of QTcpSocket::waitForBytesWritten?
Asked Answered
F

1

10

I'm a little confused on the behavior of QTcpSocket::waitForBytesWritten()...

Until when does this function block?

  • Until the data is written to the OS's internal buffer for transmission over TCP?
  • Until the data is physically converted to TCP packets and sent?
  • Until the entire data is transmitted and the remote client acknowledges that all packets have been received?

I looked at the documentation, but it didn't seem to be very clear.

Fante answered 11/1, 2011 at 3:43 Comment(0)
W
7

Generally speaking OSes only provide easy APIs for the first question - since Qt is a portable API, it's best only to rely on it referring to the transfer to the OS's buffer. If you need an actual acknowledgement of receipt, it's best to have it sent by the remote application - after all, data can be ack'd by the remote but never read off the remote's OS read buffer.

If you need to avoid having the remote side block you forever, you should instead wait for the QIODevice::bytesWritten signal and return to the event loop to do other work, or simply set an appropriate timeout. In general, the remote side can always block you at some level - ie, it can refuse to ack, filling up your local OS buffer, at which point writes won't make it from Qt to the OS; no matter what level waitForBytesWritten() is at, it can always be blocked.

As such, bytesWritten and waitForBytesWritten() should only be used to throttle the source of the data - ie, if you were to go into a tight loop passing 1G of data to the socket all at once, you might end up buffering it in the process and running out of memory. By triggering additional reads/writes with the bytesWritten signal, you can avoid this issue.

Weissmann answered 11/1, 2011 at 5:15 Comment(1)
I don't need acknowledgement of receipt. What I really want is to avoid the situation where a client can delay the application by waiting to send the ACK.Fante

© 2022 - 2024 — McMap. All rights reserved.