Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- #include <netdb.h>
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <pthread.h>
- #include <string.h>
- #define SERVER_PORT 4012
- #define SERVER_ADDRESS "127.0.0.1"
- #define MAXLINE 512
- void* recibir(void* p);
- void* enviar(void* p);
- int flag=0;
- int main()
- {
- struct sockaddr_in addr;
- int sd,status;
- pthread_t hilos[2];
- addr.sin_family = AF_INET;
- addr.sin_addr.s_addr = inet_addr(SERVER_ADDRESS);
- addr.sin_port = htons(SERVER_PORT);
- if((sd = socket (AF_INET, SOCK_STREAM, 0)) == -1)
- {
- printf("Error al crear el socket\n");
- exit(0);
- }
- if(connect(sd, (struct sockaddr *)&addr, sizeof(addr)) == -1)
- {
- printf("Error al conectar\n");
- exit(0);
- }
- else
- {
- if ( (status = pthread_create(&hilos[0],NULL,recibir,(void*)&sd)) ) //La función pthread_create() devuelve 0 si todo ha ido bien. Un valor distinto de 0 si ha habido algún problema y no se ha creado el thread.
- {
- printf("Error al crear hilo para recibir\n");
- close(sd);
- exit(0);
- }
- /*
- if ( (status = pthread_create(&hilos[1],NULL,enviar,(void*)&sd)) )
- {
- printf("Error al crear hilo para enviar\n");
- close(sd);
- exit(0);
- }*/
- pthread_join(hilos[0],NULL);
- //pthread_join(hilos[1],NULL);
- }
- return 1;
- }
- void* recibir(void* p)
- {
- int* id;
- char buffer[MAXLINE];
- id = (int*) p;
- send(*id,"me conecte",MAXLINE,0);
- while(1)
- {
- recv(*id,buffer,MAXLINE,0);
- printf("\n%s\n",buffer);
- memset(buffer,'\0',sizeof(buffer));
- printf("\nTexto: ");
- gets(buffer);
- send(*id,buffer,MAXLINE,0);
- memset(buffer,'\0',sizeof(buffer));
- }
- }
- void* enviar(void* p)
- {
- int* id;
- char buffer2[MAXLINE];
- id = (int*) p;
- while(1)
- {
- printf("\nTexto: ");
- gets(buffer2);
- send(*id,buffer2,MAXLINE,0);
- memset(buffer2,'\0',sizeof(buffer2));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement