Newer
Older
#include "client.hpp"
#include "definitions.hpp"
#include "server.hpp"
#include <cstdio>
#include <unistd.h>
/**
* @brief Construct a new Client object with defailt port and address
*
*/
Client::Client() : sock(), serverAddr() {
sock = socket(AF_INET, SOCK_STREAM, 0);
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(DEFAULT_PORT);
inet_aton(DEFAULT_IP, &serverAddr.sin_addr);
}
/**
* @brief Construct a new Client object with custom port and address
*
*/
Client::Client(const std::string &addr, const int &port) {
sock = socket(AF_INET, SOCK_STREAM, 0);
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(port);
inet_aton(addr.c_str(), &serverAddr.sin_addr);
/**
* @brief Connects to server
*
* @return int
*/
int rc = connect(sock, (struct sockaddr *)&serverAddr, sizeof(serverAddr));
if (rc < 0) {
perror("connect() failed");
}
/**
* @brief Disconnects from server
*
* @return int
*/
int Client::disconnectFromServer() {
int rc = close(sock);
if (rc < 0) {
perror("disconnect() failed");
}
return rc;
}
/**
* @brief Sends protobuf message to server
*
* @param msg
* @return uint16_t bytes send
*/
uint16_t Client::sendMessage(const proto::Message &msg) {
uint8_t buf[msg.ByteSizeLong()];
msg.SerializeToArray(buf, msg.ByteSizeLong());
auto bytes = send(sock, buf, msg.ByteSizeLong(), 0);
/**
* @brief Receives message from server (blocking)
*
* @return int < 0 signals error
*/
int nbytesrecv = recv(sock, inputBuffer, INPUT_BUFFER_SIZE, 0);
if (nbytesrecv <= 0) {
disconnectFromServer();
perror("recv() failed");
assert(onReceiveCB != nullptr);
onReceiveCB(sock, inputBuffer);
bzero(&inputBuffer, INPUT_BUFFER_SIZE);
/**
* @brief Sets callback for receiving data
*
* @param fn
*/
void Client::onReceive(receiveCallbackType fn) { onReceiveCB = fn; }