Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behavior of QTcpSocket::waitForBytesWritten?

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.

like image 930
Nathan Osman Avatar asked Jan 11 '11 03:01

Nathan Osman


1 Answers

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.

like image 143
bdonlan Avatar answered Oct 07 '22 19:10

bdonlan