mcping/Connection.cpp

69 lines
1.4 KiB
C++

#include "Connection.h"
#include <sys/socket.h>
#include <arpa/inet.h>
#include <iostream>
#include <unistd.h>
#include <string.h>
void Connection::p_HandleError(){
std::cout << "an error occured during execution" << std::endl;
switch (error) {
case ErrorTypes::socket_creation:
perror("error while trying to create a file descriptor");
break;
case ErrorTypes::get_ip:
perror("error while trying to get ip");
break;
case ErrorTypes::connect:
perror("error while trying to connect");
break;
default:
std::cerr << "An unknown error occured" << std::endl;
}
}
int Connection::status(){
return static_cast<int>(error);
}
Connection::Connection(std::string server_ip, int port){
fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0){
error = ErrorTypes::socket_creation;
}
in_addr in_a;
if(!inet_aton(server_ip.data(), &in_a)){
error = ErrorTypes::get_ip;
}
sockaddr_in addr({ AF_INET, htons(port), in_a });
if(connect(fd, (sockaddr*) &addr, sizeof(addr)) != 0){
error = ErrorTypes::connect;
}
}
Connection::~Connection(){
close(fd);
}
bool Connection::send(std::vector<Payload> payloads){
for (Payload& p : payloads) {
::send(fd, p.getData() , p.getSize(), 0);
}
return true;
}
Payload Connection::recv(){
Payload ret;
char temp[100];
memset(temp, 0, 100);
ssize_t size;
while((size = ::recv(fd, temp, sizeof(temp), 0)) > 0){
for(char& in: temp){
ret.push_char(in);
}
}
return ret;
}