Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 40 additions & 4 deletions Client/client.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,55 @@ Client::Client(quint16 clientPort, const QVector<quint16>& 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<QTcpSocket*>(sender());
if (!serverConnection) {
return;
}
m_serversMap[serverId] = serverConnection;*/

QTcpSocket* serverConnection = dynamic_cast<QTcpSocket*>(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;
}


// если сообщение об ошибке, то проталкиваем его дальше согласно маршруту

Expand All @@ -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();
}
}

2 changes: 1 addition & 1 deletion Client/client.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down