Created
November 5, 2012 22:38
-
-
Save dflima/4020871 to your computer and use it in GitHub Desktop.
Aula de Sockets (Paralelo) - Server
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 | |
#define MAXBUF 20 | |
#define MAXCONECT 5 | |
int esock,nsock, test, tam; | |
struct sockaddr_in server, client; | |
char buffer[MAXBUF]; | |
void* enviar(void* arg) { | |
while(1) { | |
printf("\nEu: "); | |
gets(buffer); | |
if(send(nsock, buffer, sizeof(buffer),0)<0){ | |
perror("Erro no envio de dados"); | |
exit(1); | |
} | |
} | |
} | |
void* receber(void* arg) { | |
while(1) { | |
if(recv(nsock,buffer,sizeof(buffer),0)<0){ | |
perror("Erro no recebimento de dados"); | |
exit(1); | |
} | |
printf("\nO outro disse: %s\n", buffer); | |
} | |
} | |
main(){ | |
pthread_t t_enviar, t_receber; | |
/* cria o socket */ | |
if ((esock = socket(AF_INET, SOCK_STREAM, 0)) < 0){ | |
perror("Erro na criacao do socket no servidor"); | |
exit(1); | |
} | |
/* inicializa a estrutura endereco/porta */ | |
server.sin_family = AF_INET; | |
server.sin_port = htons(PORTA); | |
server.sin_addr.s_addr = INADDR_ANY; | |
bzero(&(server.sin_zero), 8); | |
/* associa um número de porta ao socket */ | |
if(bind(esock, (struct sockaddr*)&server, sizeof(struct sockaddr)) < 0){ | |
perror("Erro na associacao do socket (Bind)"); | |
exit(1); | |
} | |
/* coloca o socket em modo "listening" */ | |
test = listen(esock, MAXCONECT); | |
if (test < 0){ | |
perror("\nErro na funcao listen."); | |
exit(1); | |
} | |
while (1){ | |
tam = sizeof(struct sockaddr_in); | |
nsock = accept(esock, (struct sockaddr *)&client, &tam); | |
if(nsock < 0){ | |
perror("Erro no accept"); | |
//continue; | |
} | |
printf("Cliente conectado em %s\n", inet_ntoa(client.sin_addr)); | |
pthread_create(&t_receber, NULL, &receber, NULL); | |
pthread_create(&t_enviar, NULL, &enviar, NULL); | |
pthread_join(t_receber, NULL); | |
pthread_join(t_enviar, NULL); | |
close(nsock); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment