« Conexão TCP/IP em Servidor Mysql Ubuntu | Modelos Matemáticos » |
Programação com Sockets em C
Na disciplina de Sistemas Distribuídos, neste semestre, tivemos que criar um programa client/server no qual o cliente deveria solicitar uma operação matemática ao usuário. Em seguida, a solicitação seria enviada ao servidor, o qual realizaria o cálculo e retornaria o resultado ao cliente.
A implementação foi feita em C com a utilização de sockets…
Programa Cliente
Code
/* | |
Trabalho Sistemas Distribuídos | |
Vilson C. Gartner | |
*/ | |
| |
#include <stdio.h> | |
#include <string.h> | |
#include <sys/socket.h> | |
#include <resolv.h> | |
| |
// Servidor e Porta para conexão | |
#define SERVIDOR "127.0.0.1" | |
#define PORTA 171 | |
| |
int main() | |
{ | |
int sockete, rs; | |
struct sockaddr_in destino; | |
char buffer[1024]; | |
char operacao[50]; | |
| |
if ( (sockete = socket(AF_INET, SOCK_STREAM, 0) ) < 0 ) | |
{ | |
perror("socket"); | |
abort(); | |
} | |
| |
destino.sin_family = AF_INET; | |
destino.sin_port = htons(PORTA); | |
| |
inet_aton(SERVIDOR, &destino.sin_addr.s_addr); | |
| |
if ( connect( sockete, (struct sockaddr*)&destino, sizeof(destino) ) < 0) | |
{ | |
perror("connect"); | |
abort(); | |
} | |
| |
recv(sockete, buffer, sizeof(buffer), 0); | |
printf("%s", buffer); | |
| |
while (1) | |
{ | |
printf("\nOperação (? para ajuda): "); | |
bzero(buffer, 1024); | |
bzero(operacao,50); | |
fgets(operacao,50,stdin); | |
| |
write( sockete, operacao, 50 ); | |
recv(sockete, buffer, sizeof(buffer), 0); | |
| |
printf("%s", buffer); | |
} | |
| |
close(sockete); | |
| |
return 0; | |
} |
Programa Servidor
Code
/* | |
Trabalho Sistemas Distribuídos | |
Vilson C. Gartner | |
*/ | |
| |
#include <stdio.h> | |
#include <sys/socket.h> | |
#include <resolv.h> | |
#include <errno.h> | |
#include <time.h> | |
| |
// Porta de comunicação | |
#define PORTA 171 | |
| |
// Função para ver tamanho da string | |
int strlen(char str[]) | |
{ | |
int i; | |
| |
for(i = 0; str[i] != '\0'; i++) | |
{} | |
| |
return i; | |
} | |
| |
// Função para retornar a posição de caracter na string | |
int strpos(char s[], char t[]) | |
{ | |
int i,j,k; | |
| |
for(i=0;s[i]!='\0';i++) | |
{ | |
for(j=i,k=0;t[k]!='\0' && s[j]==t[k];j++,k++) | |
; | |
if(k>0 && t[k]=='\0') | |
{ | |
return i; | |
} | |
} | |
| |
return -1; | |
} | |
| |
// Função para extrair parte da string | |
substr(char dest[], char src[], int offset, int len) | |
{ | |
int i; | |
| |
for(i = 0; i < len && src[offset + i] != '\0'; i++) | |
{ | |
dest[i] = src[i + offset]; | |
} | |
| |
dest[i] = '\0'; | |
} | |
| |
// Função auxiliar para a itoa | |
void strreverse(char* begin, char* end) | |
{ | |
| |
char aux; | |
| |
while(end>begin) | |
{ | |
aux=*end, *end--=*begin, *begin++=aux; | |
} | |
} | |
| |
// Função para converter integer para char | |
void itoa(int value, char* str, int base) | |
{ | |
static char num[] = "0123456789abcdefghijklmnopqrstuvwxyz"; | |
| |
char* wstr=str; | |
| |
int sign; | |
| |
if (base<2 || base>35) | |
{ | |
*wstr='\0'; return; | |
} | |
| |
if ((sign=value) < 0) value = -value; | |
| |
do *wstr++ = num[value%base]; while(value/=base); | |
| |
if(sign<0) *wstr++='-'; | |
| |
*wstr='\0'; | |
| |
strreverse(str,wstr-1); | |
} | |
| |
// Função principal | |
int main() | |
{ | |
int sockete, conexao; | |
struct sockaddr_in self; | |
char buffer[1024]; | |
char hora[30]; | |
char resultado[1024]; | |
| |
char *sub_str; | |
struct sockaddr_in client_addr; | |
int addrlen=sizeof(client_addr); | |
| |
sockete = socket(AF_INET, SOCK_STREAM, 0); | |
| |
self.sin_family = AF_INET; | |
self.sin_port = htons(PORTA); | |
self.sin_addr.s_addr = INADDR_ANY; | |
| |
bind(sockete, (struct sockaddr*)&self, sizeof(self)); | |
| |
if ( listen(sockete, 20) < 0 ) | |
{ | |
perror("listen"); | |
abort(); | |
} | |
| |
printf("Aguardando conexao...\n", sockete); | |
| |
conexao = accept(sockete, (struct sockaddr*)&client_addr, &addrlen); | |
| |
printf("Conectado: %s:%d\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port)); | |
| |
time_t agora = time(NULL); | |
struct tm tim = *( localtime(&agora) ); | |
strftime(hora, 40, "Bem-vindo\nAgora são %H:%M:%S \n", &tim); | |
write(conexao, hora, 40); | |
| |
int pos, num1, num2, res, tam, len; | |
char str1[10]; | |
char str2[10]; | |
char strres[10]; | |
| |
while (1) | |
{ | |
bzero(buffer, 1024); | |
read(conexao, buffer, 255); | |
| |
printf("Solicitação do cliente: %s",buffer); | |
| |
if ( strstr(buffer, "+") ) | |
{ | |
pos = strpos(buffer, "+"); | |
substr(str1, buffer, 0, pos ); | |
| |
len = strlen(buffer) - strlen(str1); | |
substr(str2, buffer, pos+1, len-1 ); | |
| |
num1 = atoi(str1); | |
num2 = atoi(str2); | |
res = num1 + num2; | |
| |
itoa(res, strres, 10 ); | |
| |
write(conexao, strres, sizeof(strres) ); | |
} | |
else if ( pos = strstr(buffer, "-") ) | |
{ | |
pos = strpos(buffer, "-"); | |
substr(str1, buffer, 0, pos ); | |
| |
len = strlen(buffer) - strlen(str1); | |
substr(str2, buffer, pos+1, len-1 ); | |
| |
num1 = atoi(str1); | |
num2 = atoi(str2); | |
res = num1 - num2; | |
| |
itoa(res, strres, 10 ); | |
| |
write(conexao, strres, sizeof(strres) ); | |
} | |
else if ( pos = strstr(buffer, "*") ) | |
{ | |
pos = strpos(buffer, "*"); | |
substr(str1, buffer, 0, pos ); | |
| |
len = strlen(buffer) - strlen(str1); | |
substr(str2, buffer, pos+1, len-1 ); | |
| |
num1 = atoi(str1); | |
num2 = atoi(str2); | |
res = (num1 * num2); | |
| |
itoa(res, strres, 10 ); | |
| |
write(conexao, strres, sizeof(strres) ); | |
} | |
else if ( pos = strstr(buffer, "/") ) | |
{ | |
pos = strpos(buffer, "/"); | |
substr(str1, buffer, 0, pos ); | |
| |
len = strlen(buffer) - strlen(str1); | |
substr(str2, buffer, pos+1, len-1 ); | |
| |
num1 = atoi(str1); | |
num2 = atoi(str2); | |
res = num1 / num2; | |
| |
itoa(res, strres, 10 ); | |
| |
write(conexao, strres, sizeof(strres) ); | |
} | |
else | |
{ | |
printf("Mostrando ajuda ao cliente\n"); | |
strcpy(resultado, "\nExemplos de utilização: \nSoma: 12+4 \nMultiplicação: 12*4 \nDivisão: 12/4 \nSubtração: 12-4\n\n"); | |
write(conexao, resultado, sizeof(resultado) ); | |
} | |
} | |
| |
close(conexao); | |
close(sockete); | |
return 0; | |
} |
This entry was posted on 05 Oct 2007 at 00:48 by admin and is filed under Programação, C.
No feedback yet
Comments are closed for this post.