client.cpp 2.59 KB
/** @file 
* \brief Fichero de implementación de un cliente
* \author Imanol Barba Sabariego
* \date 13/06/2013
*
* En este fichero se implementa un cliente para poder usar con el servidor creado, usando la clase Socket.
*/
#include "Socket.h"
#include <iostream>
#include "SocketException.h"
#include <sstream>
#include <signal.h>

#include <sys/time.h>

using namespace std;

//! Método para terminar el cliente
/*! Este método se usa para terminar el cliente immediatamente en el caso que el servidor cierre la conexión de forma inesperada, capturando
el signal SIGPIPE. */
void exitClient(int signal/*!<Parámetro que captura el signal recibido*/)
{
	cout << "Server connection terminated unexpectedly" << endl << "Exiting" << endl;
	exit(-1);
}

//! Método principal del cliente
/*! Este método inicializa el Socket, establece la conexión y realiza las acciones que se le hayan programado para comunicarse con el servidor.*/
int main()
{
	signal(SIGPIPE, exitClient);
	Socket s;
	string send, recv, host;
	int port;
	s.Create();
	cout << "Created socket" << endl;
	cout << "Hostname: ";
	cin >> host;
	cout << "Port: ";
	cin >> port;
	cin.ignore();
	try
	{
		s.Connect(host,port);
	}
	catch(SocketException& e)
	{
		cout << e.description() << endl;
		return -1;
	}
	cout << "Connected" << endl;
	while(true)
	{
		cout << "> ";
		getline(cin,send);
		if(cin.eof())
		{
			send = "exit";
		}
		try
		{
			s << send;
			if(send == "exit")
			{
				s >> recv;
				if(recv == "OK")
				{
					cout << "Exiting" << endl;
					s.Close();
	           	 	cout << "Socket closed" << endl;
	            	return 0;
				}
			}
			else if(send == "test")
			{
				string data = "", answer;
				double size;
				double start, duration;
				cout << "Size in MB: ";
				cin >> size;
				cin.ignore();
				for(long int i = 0; i < size*1e6; i++ )
				{
					data += (char)( 65 + i % 26);
				}
				cout << "Data generated, commencing transfer" << endl;
				struct timeval  st, ed;
				gettimeofday(&st, NULL);
				s << data;
				cout << "Data sent" << endl;
				s >> answer;
				gettimeofday(&ed, NULL);
				start = (st.tv_sec) + (st.tv_usec) / 1e6;
				duration = ((ed.tv_sec) + (ed.tv_usec) / 1e6) - start;
				if(answer == "ACK")
				{
					cout << "Transferred " << size << " MB  in " << duration << " seconds" << endl;
					cout << "Data rate: " << size/duration << " MB/s" <<  endl;
				}
			}
			else
			{
				s >> recv;
				cout << "Received: " << recv << endl;
			}
		}
		catch(SocketException& e)
		{
			cout << e.description() << endl;
			cout << "Exiting" << endl;
			s.Close();
       	 	cout << "Socket closed" << endl;
        	return -1;
		}
	}
}