Código:
#include <sys/types.h> #include <sys/socket.h> #include <stdio.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <stdlib.h> void *writetoserver(void *arg); void *readfromserver(void *arg); int sockfd; int main() { int len; struct sockaddr_in address; int result; char* nickname; pthread_t wThread, rThread; //Pide usuario printf("Escribe un nickname para iniciar el nuevo Messenger: "); scanf("%s",&nickname); /* Crear un socket para el cliente */ sockfd = socket(AF_INET, SOCK_STREAM, 0); /* Nombrar el socket, de acuerdo con el server */ address.sin_family = AF_INET; address.sin_addr.s_addr = inet_addr("127.0.0.1"); address.sin_port = htons(9734); len = sizeof(address); result = connect(sockfd, (struct sockaddr *)&address, len); if(result == -1) { perror("oops: client1"); exit(1); } write(sockfd, nickname, 1); read(sockfd, nickname, 1); /* Crea un hilo que espera a que el cliente escriba */ pthread_create(&wThread,NULL,writetoserver,NULL); /* Crea un hilo que espera a que el servidor mande mensajes */ pthread_create(&rThread,NULL,writetoserver,NULL); pthread_join(wThread,NULL); pthread_join(rThread,NULL); close(sockfd); return 0; } void *writetoserver(void *arg) { char* msg; while(strcmp(msg,"exit")!= 0) { printf("Escribe tu mensaje"); scanf("%s",msg); write(sockfd, msg, 1); } } void *readfromserver(void *arg) { char* in; while(strcmp(in,"exit")!=0) { read(sockfd, in, 1); if(strcmp(in,"msj") == 1) { read(sockfd, in, 1); printf(" %s",in); } } }