#include "clientprotocol.h" #include "gamedata.h" #include "getitem.h" #include "login.h" #include "player.h" #include "updateplayerdata.h" #include #include #include #include #include #define DEFAULT_GAME_PORT 7777 namespace ClientProtocol { Header::Header() { reset(); } bool Header::isValid() const { if (sizeof (*this) != 4) { return false; } if (static_cast(command) == Command::Undefined) { return false; } if (static_cast(type) == Type::Undefined) { return false; } return isValidSize(command, size); } void Header::reset() { size = 0; command = static_cast(Command::Undefined); type = static_cast(Type::Responke); } Package::Package() { reset(); } bool Package::isValid() const { if (!hdr.isValid()) { return false; } if (data.size() && hdr.command != data.at(0)) { return false; } return hdr.size == static_cast (data.size()); } BaseNetworkObject* Package::parse() const { if (!isValid()) return nullptr; auto obj = FactoryNetObjects::build(hdr.command); if (!obj) { return nullptr; } QDataStream stream(data); obj->readFromStream(stream); return obj; } bool Package::create(const BaseNetworkObject *obj, Type type) { if (!obj) { return false; } auto command = obj->getClass(); if (command < 0) { return false; } QDataStream stream(&data, QIODevice::ReadWrite); obj->writeToStream(stream); hdr.command = static_cast(command); hdr.type = static_cast(type); hdr.size = static_cast(data.size()); return isValid(); } bool Package::create(Command cmd, Type type, const QByteArray &data) { hdr.command = static_cast(cmd); hdr.type = static_cast(type); hdr.size = static_cast(data.size()); this->data = data; return isValid(); } bool Package::create(Command cmd, Type type) { if (cmd == Command::Undefined) { return false; } hdr.command = static_cast(cmd); hdr.type = static_cast(type); hdr.size = static_cast(data.size()); return isValid(); } QByteArray Package::toBytes() const { QByteArray res; res.append(reinterpret_cast(const_cast(&hdr)), sizeof (hdr)); res.append(data); return res; } void Package::reset() { hdr.reset(); data.clear(); } bool isValidSize(quint8 type, unsigned int size) { if (!FactoryNetObjects::isInited()) { return false; } if (!FactoryNetObjects::isRegisteredType(type)) { return size == 0; } return FactoryNetObjects::getSize(type).isValid(size); } bool initClientProtockol() { if (!FactoryNetObjects::regType( static_cast(Command::Login))) { return false; } if (!FactoryNetObjects::regType( static_cast(Command::UpdatePlayerData))) { return false; } if (!FactoryNetObjects::regType( static_cast(Command::GameData))) { return false; } if (!FactoryNetObjects::regType( static_cast(Command::GetItem))) { return false; } if (!FactoryNetObjects::regType( static_cast(Command::Player))) { return false; } if (!FactoryNetObjects::regType( static_cast(Command::Snake))) { return false; } if (!FactoryNetObjects::regType( static_cast(Command::Map))) { return false; } return true; } }