cpp-console-game/eRPC/Client.cpp

67 lines
1.5 KiB
C++
Raw Permalink Normal View History

2024-07-05 20:37:02 +01:00
#include "Client.hpp"
#include "Request.hpp"
#include "Response.hpp"
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdexcept>
#include <unistd.h>
int msgIdCounter = 0;
2024-07-05 20:37:02 +01:00
namespace eRPC
{
Client::Client(std::string host, int port) : sockfd(-1), serverAddress()
2024-07-05 20:37:02 +01:00
{
sockaddr_in serverAddress;
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(port);
2024-07-05 20:37:02 +01:00
if (inet_pton(AF_INET, host.c_str(), &serverAddress.sin_addr) <= 0)
2024-07-05 20:37:02 +01:00
{
throw std::runtime_error("Invalid address");
}
this->serverAddress = serverAddress;
2024-07-05 20:37:02 +01:00
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
2024-07-05 20:37:02 +01:00
{
throw std::runtime_error("Failed to create socket");
2024-07-05 20:37:02 +01:00
}
if (connect(sockfd, (sockaddr *)&serverAddress, sizeof(serverAddress)) < 0)
2024-07-05 20:37:02 +01:00
{
throw std::runtime_error("Failed to connect to server");
}
}
Client::~Client()
2024-07-05 20:37:02 +01:00
{
Request request(msgIdCounter++, "disconnect", {});
auto serialized = request.serialize();
write(sockfd, serialized.c_str(), serialized.size() + 1);
2024-07-05 20:37:02 +01:00
close(sockfd);
sockfd = -1;
2024-07-05 20:37:02 +01:00
}
std::string Client::call(std::string method, std::vector<std::string> params)
2024-07-05 20:37:02 +01:00
{
Request request(msgIdCounter++, method, params);
2024-07-05 20:37:02 +01:00
auto serialized = request.serialize();
write(sockfd, serialized.c_str(), serialized.size() + 1);
char buffer[1024] = {0};
read(sockfd, buffer, 1024);
Response response(buffer);
if (!response.isOk())
{
throw std::runtime_error(response.getResult());
}
return response.getResult();
2024-07-05 20:37:02 +01:00
}
}