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!
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