Good day to all! Guys, I need help. So, there is a client class through which the application communicates with the server.

class Cls { explicit Cls(QObject* parent = nullptr, const QString& host = QString("localhost"), const quint16 port = 8008); ~Cls(); signals: void send(const QString&); void read(); public slots: void sendData(const QString& data); Q_INVOKABLE void readData(); private: QTcpSocket* mSocket; QString mHost; quint16 mPort; QMutex mMutex; } void Cls::sendData(const QString& data) { QMutexLocker locker(&mMutex); if(mSocket->state() == QAbstractSocket::ConnectedState) { QByteArray bytes(data.toStdString().c_str()); mSocket->write(bytes); mSocket->flush(); } } void Cls::readData() { QMutexLocker locker(&mMutex); if (mSocket->state() == QAbstractSocket::ConnectedState) { const quint32 bytes = mSocket->bytesAvailable(); QByteArray raw_data(QByteArray::fromRawData(mSocket->readAll(), bytes)); QJsonDocument document = QJsonDocument::fromJson(raw_data); ... } } 

Main connections:

 connect(mSocket, &QTcpSocket::readyRead, this, &Cls::readData, Qt::QueuedConnection); connect(this, &Cls::send, this, &Cls::sendData, Qt::QueuedConnection); 

Further, there are 2 functions that are called from different threads, and in these 2 functions Cls is called:

 SomeType foo_1(params) { ... emit mCls.send("#command_1") ... } SomeType foo_2(params) { ... emit mCls.send("#command_1") ... emit mCls.send("#command_2") ... } 

But, since If this is caused in different threads, then these threads can be said to "tear" the socket. Please tell me the ideas how to correctly work from the architectural point of view, to organize the work of the Cls class, so that the read * / send * slots would work out correctly, the data was sent correctly and arrived accordingly.

Thank!

  • you need to make a queue (roughly speaking, QList<QByteArray> may be the appropriate solution. The "send" commands will be added to the queue And then he will send the message. Consumer-Producer. But usually, if only sending from different streams, everything works fine and so - KoVadim
  • Thank! We dealt with this, heroically rewriting several small parts. - jaroslav
  • Now the question is different. The socket sends the data to the server for the first time, the server receives and responds safely. Everything is good. But .. when the second data is sent, the socket seems to go into a loop and, accordingly, there is no data on the server, readyRead () is not emitted, data is not read. - jaroslav
  • And who knows what is written there now. At least I would take a sniffer (wireshark) and see what is running there and where - KoVadim
  • @KoVadim Thank you for inspiration) Zasnifili, saw that podlagivaet server, corrected the server, everything started - jaroslav

0