ethanglide
c9a50d363e
Got multiple remote calls from one client working Improved error messages Got function name and arguments sent over as well as return values
75 lines
1.5 KiB
C++
75 lines
1.5 KiB
C++
#include "Client.hpp"
|
|
#include "Request.hpp"
|
|
#include "Response.hpp"
|
|
|
|
#include <sys/socket.h>
|
|
#include <arpa/inet.h>
|
|
#include <stdexcept>
|
|
#include <unistd.h>
|
|
#include <iostream>
|
|
|
|
int msgIdCounter = 0;
|
|
|
|
namespace eRPC
|
|
{
|
|
Client::Client(std::string host, int port) : sockfd(-1), serverAddress()
|
|
{
|
|
sockaddr_in serverAddress;
|
|
serverAddress.sin_family = AF_INET;
|
|
serverAddress.sin_port = htons(port);
|
|
|
|
if (inet_pton(AF_INET, host.c_str(), &serverAddress.sin_addr) <= 0)
|
|
{
|
|
throw std::runtime_error("Invalid address");
|
|
}
|
|
|
|
this->serverAddress = serverAddress;
|
|
}
|
|
|
|
Client::~Client()
|
|
{
|
|
closeConnection();
|
|
}
|
|
|
|
void Client::openConnection()
|
|
{
|
|
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
|
|
{
|
|
throw std::runtime_error("Failed to create socket");
|
|
}
|
|
|
|
if (connect(sockfd, (sockaddr *)&serverAddress, sizeof(serverAddress)) < 0)
|
|
{
|
|
throw std::runtime_error("Failed to connect to server");
|
|
}
|
|
}
|
|
|
|
void Client::closeConnection()
|
|
{
|
|
close(sockfd);
|
|
sockfd = -1;
|
|
}
|
|
|
|
std::string Client::call(std::string method, std::vector<std::string> params)
|
|
{
|
|
Client::openConnection();
|
|
|
|
Request request(msgIdCounter++, method, params);
|
|
auto serialized = request.serialize();
|
|
write(sockfd, serialized.c_str(), serialized.size() + 1);
|
|
|
|
char buffer[1024] = {0};
|
|
read(sockfd, buffer, 1024);
|
|
|
|
Client::closeConnection();
|
|
|
|
Response response(buffer);
|
|
|
|
if (!response.isOk())
|
|
{
|
|
throw std::runtime_error(response.getResult());
|
|
}
|
|
|
|
return response.getResult();
|
|
}
|
|
} |