48 lines
1.1 KiB
C++
48 lines
1.1 KiB
C++
#include "NetworkProtocol.h"
|
|
#include <exception>
|
|
|
|
|
|
namespace FRG {
|
|
|
|
std::string makeStateMessage(const nlohmann::json& state)
|
|
{
|
|
return nlohmann::json{
|
|
{"protocolVersion", kGameProtocolVersion},
|
|
{"type", "state"},
|
|
{"payload", state}
|
|
}.dump();
|
|
}
|
|
|
|
bool parseStateMessage(
|
|
const std::string& message, nlohmann::json& state,
|
|
std::string& error)
|
|
{
|
|
try {
|
|
const nlohmann::json envelope = nlohmann::json::parse(message);
|
|
if (!envelope.is_object()) {
|
|
error = "message must be a JSON object";
|
|
return false;
|
|
}
|
|
if (envelope.value("protocolVersion", -1) != kGameProtocolVersion) {
|
|
error = "unsupported protocol version";
|
|
return false;
|
|
}
|
|
if (envelope.value("type", std::string()) != "state") {
|
|
error = "unsupported message type";
|
|
return false;
|
|
}
|
|
if (!envelope.contains("payload") || !envelope["payload"].is_object()) {
|
|
error = "state payload must be an object";
|
|
return false;
|
|
}
|
|
state = envelope["payload"];
|
|
error.clear();
|
|
return true;
|
|
} catch (const std::exception& exception) {
|
|
error = exception.what();
|
|
return false;
|
|
}
|
|
}
|
|
|
|
} // namespace FRG
|