owlps/owlps-positioning/src/outputudpsocket.cc

86 lines
1.6 KiB
C++
Raw Normal View History

#include "outputudpsocket.hh"
2011-03-15 15:27:42 +01:00
#include "request.hh"
2011-03-15 15:27:42 +01:00
#include <sstream>
#include <iostream>
#define PORT 9910
2011-03-15 15:27:42 +01:00
using namespace std ;
struct hostent *hostInfo ;
struct sockaddr_in serverAddress ;
/* *** Constructors *** */
OutputUDPSocket::OutputUDPSocket(const string &_remote_ip):
remote_ip(_remote_ip)
2011-03-15 15:27:42 +01:00
{
init_socket() ;
}
2011-03-15 15:27:42 +01:00
OutputUDPSocket::~OutputUDPSocket()
2011-03-15 15:27:42 +01:00
{
kill_socket() ;
2011-03-15 15:27:42 +01:00
}
/* *** Operations *** */
void OutputUDPSocket::write(const Result &result)
2011-03-15 15:27:42 +01:00
{
string timestampXYZ;
2011-03-15 15:27:42 +01:00
ostringstream os;
const Request *const request = result.get_request() ;
2011-03-15 15:27:42 +01:00
Point3D position = result.get_position() ;
2011-03-15 15:27:42 +01:00
os
<< request->get_time_sent() << ';'
<< position.get_x() << ';'
<< position.get_y() << ';'
<< position.get_z() ;
timestampXYZ = os.str() ;
2011-03-15 15:27:42 +01:00
cout << timestampXYZ << '\n' ;
send_data(timestampXYZ);
2011-03-15 15:27:42 +01:00
}
void OutputUDPSocket::init_socket()
2011-03-15 15:27:42 +01:00
{
cout << "Initialisation socket..." << endl;
hostInfo = gethostbyname(remote_ip.c_str());
2011-03-15 15:27:42 +01:00
serverPort = PORT;
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(serverPort);
}
void OutputUDPSocket::send_data(string data)
2011-03-15 15:27:42 +01:00
{
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);
}