owlps/owlps-positioning/src/outputudpsocket.cc

84 lines
1.7 KiB
C++

#include "outputudpsocket.hh"
#include "request.hh"
#include <sstream>
#include <iostream>
using namespace std ;
struct hostent *hostInfo ;
struct sockaddr_in serverAddress ;
/* *** Constructors *** */
OutputUDPSocket::OutputUDPSocket(const string &_remote_host,
const uint_fast16_t _remote_port):
remote_host(_remote_host), remote_port(_remote_port)
{
init_socket() ;
}
OutputUDPSocket::~OutputUDPSocket()
{
kill_socket() ;
}
/* *** Operations *** */
void OutputUDPSocket::write(const Result &result)
{
string timestampXYZ;
ostringstream os;
const Request *const request = result.get_request() ;
Point3D position = result.get_position() ;
os
<< request->get_time_sent() << ';'
<< position.get_x() << ';'
<< position.get_y() << ';'
<< position.get_z() ;
timestampXYZ = os.str() ;
cout << timestampXYZ << '\n' ;
send_data(timestampXYZ);
}
void OutputUDPSocket::init_socket()
{
cout << "Initialisation socket..." << endl;
hostInfo = gethostbyname(remote_host.c_str());
socketDescriptor = socket(AF_INET, SOCK_DGRAM, 0);
serverAddress.sin_family = hostInfo->h_addrtype;
memcpy((char *) &serverAddress.sin_addr.s_addr,
hostInfo->h_addr_list[0], hostInfo->h_length);
serverAddress.sin_port = htons(remote_port);
}
void OutputUDPSocket::send_data(string data)
{
if (sendto(socketDescriptor, data.c_str(), data.size(), 0,
(struct sockaddr *) &serverAddress,
sizeof(serverAddress)) < 0)
{
cerr << "Émission du message impossible\n";
close(socketDescriptor);
}
}
void OutputUDPSocket::kill_socket()
{
cout << "Fermeture de la socket..." << endl;
close(socketDescriptor);
}