diff --git a/Client/client.cpp b/Client/client.cpp index 79eb121..b8868dd 100644 --- a/Client/client.cpp +++ b/Client/client.cpp @@ -6,27 +6,55 @@ Client::Client(quint16 clientPort, const QVector& portsVec, QObject *pa /* TODO Создать сокет для каждого сервера * Привязать сигнал ReadyRead к слоту readyRead() */ //for .... Перебираем порты из аргумента + + for (int i = 0; i < portsVec.size(); i++) + { QTcpSocket* serverConnection = new QTcpSocket(this); serverConnection->bind(QHostAddress::LocalHost, clientPort); - serverConnection->connectToHost(QHostAddress::LocalHost, portsVec[/*i*/]); //! + serverConnection->connectToHost(QHostAddress::LocalHost, portsVec[i]); //! connect(serverConnection, &QTcpSocket::readyRead, this, &Client::onRead); connect(serverConnection, &QTcpSocket::disconnected, serverConnection, &QObject::deleteLater); + } } Client::~Client() { - desconnectAll(); + disconnectAll(); } void Client::onRead() { /* Если посылка содержит id сервера, * то записываем id и сокет в m_serversMap */ //получаем сокет, от которого пришло сообщение + /*QTcpSocket* serverConnection = dynamic_cast(sender()); + if (!serverConnection) { + return; + } + m_serversMap[serverId] = serverConnection;*/ + QTcpSocket* serverConnection = dynamic_cast(sender()); + QDataStream in(serverConnection); + in.setVersion(QDataStream::Qt_6_4); if (!serverConnection) { return; } - m_serversMap[/*serverId*/] = serverConnection; + + QString message; + + in >> message; + //парсим сообщение + QStringList id_from_message = message.split("#"); //пусть после id добавляется спецсимвол # + bool ok; + int serverId = id_from_message[0].toInt(&ok,10); + if(ok == true) + { + m_serversMap[serverId] = serverConnection; + } + else + { + qDebug() << "Recieve message is: " << message; + } + // если сообщение об ошибке, то проталкиваем его дальше согласно маршруту @@ -38,8 +66,16 @@ quint64 Client::sendMessage(quint16 serverId, const QString& message) return 0; QByteArray block; QDataStream out(&block, QIODevice::WriteOnly); - out.setVersion(QDataStream::Qt_6_5); + out.setVersion(QDataStream::Qt_6_4); out << message; return m_serversMap[serverId]->write(block); } +void Client::disconnectAll() +{ + for(int i = 0; i < m_serversMap.size(); i++) + { + m_serversMap[i]->disconnectFromHost(); + } +} + diff --git a/Client/client.h b/Client/client.h index d3fbb86..74f14c2 100644 --- a/Client/client.h +++ b/Client/client.h @@ -15,7 +15,7 @@ class Client : public QObject ~Client(); quint64 sendMessage(quint16 serverId, const QString& message); bool connectToServer(quint16 serverPort); - void desconnectAll(); //TODO Сделать дисконнект всех сокетов в m_serversMap + void disconnectAll(); //TODO Сделать дисконнект всех сокетов в m_serversMap private slots: /* TODO