/** @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 "client.h" using namespace std; bool connected, finished; //! 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/*!s)->Close(); pthread_mutex_lock(t_arg->mutex); if(t_arg->s != 0) { delete t_arg->s; t_arg->s = 0; } if(t_arg != 0) { delete t_arg; t_arg = 0; } pthread_exit(NULL); } bool connect(Socket& s) { string host, nick; int port; /*cout << "Hostname: "; cin >> host; cout << "Port: "; cin >> port;*/ cout << "Nickname: "; cin >> nick; cin.ignore(); host = "localhost"; port = 3001; try { s.Connect(host,port); cout << "Connected" << endl; connected = true; s << nick; } catch(SocketException& e) { cout << e.description() << endl; } } void* sendThread(void* args) { string send; struct thread_args *t_arg = (struct thread_args*)args; while(true) { cout << "> "; getline(cin,send); if(cin.eof()) { send = "/disconnect"; } try { *(t_arg->s) << send; if(send == "/disconnect" || send == "/exit") { break; } } catch(SocketException& e) { cout << e.description() << endl; cout << "Exiting" << endl; (t_arg->s)->Close(); exit(-1); } } killThread(t_arg); } void* recvThread(void* args) { string recv; struct thread_args *t_arg = (struct thread_args*)args; while(true) { *(t_arg->s) >> recv; if(recv == "DISC_OK") { cout << "Disconnecting" << endl; (t_arg->s)->Close(); connected = false; pthread_cond_signal(t_arg->condition); break; } else if(recv == "EXIT_OK") { cout << "Exiting" << endl; (t_arg->s)->Close(); connected = false; finished = true; pthread_cond_signal(t_arg->condition); break; } else { *(t_arg->s) >> recv; cout << recv << endl; } } killThread(t_arg); } //! 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; connected = finished = false; pthread_mutex_t mutex; pthread_mutex_init(&mutex,0); pthread_cond_t condition; pthread_cond_init(&condition,0); thread_args *sArgs = new thread_args; thread_args *rArgs = new thread_args; pthread_t recv, send; s.Create(); while (!finished) { connect(s); pthread_mutex_lock(&mutex); sArgs->mutex = &mutex; sArgs->condition = &condition; sArgs->s = &s; rArgs->mutex = &mutex; rArgs->condition = &condition; rArgs->s = &s; pthread_create(&send,NULL,sendThread,(void *)sArgs); pthread_create(&recv,NULL,recvThread,(void *)rArgs); while(connected) { pthread_cond_wait(&condition,&mutex); } pthread_mutex_unlock(&mutex); } pthread_cond_destroy(&condition); pthread_mutex_destroy(&mutex); } /* TODO * * list nicks * unicast message */