c++ - Why QTcpSocket received wrong data? -


i'm writing simple network application. client sending server message server printing in qtextedit , responding client . i'm using qtcpserver , qtcpsocket. there problem can't solve. receiving data quint16 + qtime + qstring sending qbytearrey. use quint16 receiving size of data blocks. , reason when client send server

next block size: 16 (quint16 value) block size: 18  

server get:

next block size: 30073  (quint16 value) block size: 18  

as can see, reason server getting qdatastrem wrong variable value , 30073. don't understand why?

void widget::slotsendtoserver() {     logtextedit->append("slotsendtoserver()");     qbytearray arrblock;     qdatastream serversendstream(&arrblock, qiodevice::readwrite);     qstring messagestr = messagelineedit->text();      serversendstream << quint16(0) << qtime::currenttime()                      << messagestr;      serversendstream.device()->seek(0);     serversendstream << (quint16)(arrblock.size() - sizeof(quint16));      qdebug() << "next_block_size:"              <<(quint16)(arrblock.size() - sizeof(quint16))               << endl              << "full size of byte arrey:" << arrblock.size();      tcpsocket->write(arrblock);     messagelineedit->clear(); }    void widget::slotreadclient() {     logtextedit->append("slotreadclient()");     qtcpsocket *tcpsocket = (qtcpsocket*)sender();     qdatastream clientreadstream(tcpsocket);      while(true)     {         if (!next_block_size)         {             if (tcpsocket->bytesavailable() < sizeof(quint16))             {                 break;             }             clientreadstream >> next_block_size;         }          if (tcpsocket->bytesavailable() < next_block_size)         {             break;         }         qtime   time;         qstring messagetextstr;         clientreadstream >> time >> messagetextstr;          qstring messagecompletestr =                 time.tostring() + " " + "client has sent - "                                  + messagetextstr;         logtextedit->append("message received: ");         logtextedit->append(messagecompletestr);          next_block_size = 0;          sendtoclient(tcpsocket,                      "server response: received \""                        + messagetextstr + "\"");     } } 

you should ensure variable next_block_size initialized 0 each time socket connected.

if don't reuse same qtcpsocket object, can done in widget class constructor, or if do, in slot connected signal connected().


Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -