c++ - Qt5.2 QNetwork, how many bytes are writed? -


i working in networking software using qt5.2, so:

qtcpsocket m_socket;     m_socket.connecttohost(m_host, m_port); if (qint64 ret = m_socket.write(data, static_cast<qint64>(*n_bytes)) != -1) {     m_socket.waitforbyteswritten(timeout); } 

if bytes writed (not equal *n_bytes), m_socket.waitforbyteswritten(timeout) return false? need determine number of bytes written, algoritm, "retry write operation using number of bytes written offset start (data + offset)."

short answer: number of bytes returned qiodevice::write() number of bytes written. use that.

any bytes says written, don't need write them again. buffered , delivered possible, , there's no way take them back.

only possibility of partial write is, if connection breaks before transmitted. in case have no direct way find out how many bytes received other side. could have protocol, reconnects in case of unexpected disconnect, , asks how many bytes other side receives, higher level logic , qt not that.

if qiodevice::waitforbyteswritten() returns false, means not sent (to os or whatever) within timeout, or there disconnect. in case options are:

  • wait longer, in case sending data slow reason
  • disconnect (and possibly reconnect)

note: using qiodevice::waitforbyteswritten() can cause gui hang until returns, or docs put it:

warning: calling function main (gui) thread might cause user interface freeze.

you should use qiodevice::byteswritten() signal tracking how being sent. note if gives less bytes wrote, means should getting signal again soon, reporting more bytes written (or might disconnect signal telling nothing more written). still mustn't write bytes again.

overall, should avoid using waitforxxxx() methods of qt event loop (unless quick hack or throw-away project or that). can convenient, in end can cause unexpected problems in event-based program flow. write slots , connect signals, it's not many minutes of work.


Comments

Popular posts from this blog

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -

php - Magento - Deleted Base url key -

android - How to disable Button if EditText is empty ? -