Created
November 5, 2012 22:37
-
-
Save dflima/4020862 to your computer and use it in GitHub Desktop.
Aula de Sockets (Paralelo) - Client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <arpa/inet.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <pthread.h> | |
#define PORTA 8880 | |
int e_socket, conexao; | |
struct sockaddr_in destino; | |
char p[20]; | |
void* enviar(void* arg) { | |
while(1) { | |
printf("\nEu: "); | |
gets(p); | |
if(send(e_socket,p,sizeof(p),0)<0) { | |
perror("Erro no envio de dados"); | |
exit(1); | |
} | |
} | |
} | |
void* receber(void* arg) { | |
while(1) { | |
if(recv(e_socket,p,sizeof(p),0)<0){ | |
perror("Erro no recebimento de dados"); | |
exit(1); | |
} | |
printf("\nO outro disse: %s\n", p); | |
} | |
} | |
main(){ | |
pthread_t t_enviar, t_receber; | |
e_socket = socket(AF_INET, SOCK_STREAM, 0); | |
if (e_socket < 0){ | |
perror("Erro na criacao do socket"); | |
exit(1); | |
} | |
destino.sin_family = AF_INET; | |
destino.sin_port = htons(PORTA); | |
destino.sin_addr.s_addr = inet_addr("127.0.0.1"); | |
bzero(&(destino.sin_zero), 8); | |
conexao = connect(e_socket,(struct sockaddr *)&destino, sizeof(destino)); | |
if (conexao < 0){ | |
perror("Erro no estabelecimento de conexao"); | |
exit(1); | |
} | |
pthread_create(&t_enviar, NULL, &enviar, NULL); | |
pthread_create(&t_receber, NULL, &receber, NULL); | |
pthread_join(t_enviar, NULL); | |
pthread_join(t_receber, NULL); | |
close(e_socket); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment