client_msg.c

Go to the documentation of this file.
00001 //para compilar
00002 
00004 
00005 
00006 #define _GNU_SOURCE
00007 #include <string.h>
00008 #include <stdlib.h>
00009 #include <unistd.h> //para comando de usleep
00010 #include <ctype.h>
00011 #include <stdio.h>
00012 #include <sys/types.h>
00013 #include <sys/socket.h>
00014 #include <sys/stat.h>
00015 #include <sys/types.h>
00016 #include <netinet/in.h>
00017 #include <netdb.h>
00018 
00019 
00020 //configuração das threads.
00021 #include <pthread.h>
00022 pthread_t tid1, tid2;
00023 
00024 #include "../sft.h"
00025 
00026 struct sockaddr_in server;
00027 struct hostent *hp, *gethostbyname();
00028 
00029 
00030 char msg[TAMMSG];
00031 #define MSG_CLI 150
00032 #define FONT "database.sft"
00033 
00034 //arquivo usado para banco de dados.
00035 FILE *dtSft;
00036 
00037 //identificador para as mensagens.
00038 int id_msg =0;
00039 int flag =0, tchau, id_send;
00040 
00041 int gravar_mensagem(void);
00042 int ler_mensagens(void);
00043 void *menu();
00044 void * gerencia(void);
00045 int monta_pkt(char *aux);
00046 int send_pkt_msg(struct sft_hdr *sft);
00047 int envia_mensagem();
00048 
00054 int cria_database(void){
00055         
00056         dtSft = fopen(FONT, "w+");
00057         if(dtSft == NULL){
00058                 printf("\nNao foi possivel criar um database para o cliente.");
00059                 return -1;
00060         }
00061         
00062         fclose (dtSft);
00063         return 0;
00064 }
00065 
00066 
00067 int gera_menu(void){
00068         int i;
00069         
00070         printf("ESCOLHA UMA DAS OPCOES\n");
00071         printf("0 - Escrever mensagem.\n");
00072         printf("1 - Ler mensagens do banco de dados.\n");
00073         //printf("2 - Enviar proxima mensagem.\n");
00074         printf("2 - Sair do cliente SFT.\n");
00075         printf(":> ");
00076         scanf("%d", &i);
00077         
00078         return i;
00079 }
00080 
00081 
00082 void *menu(){
00083 //int menu(){
00084         int clt;        
00085         
00086         do{
00087                 clt = gera_menu();
00088                 
00089                 switch (clt){
00090                         case 0: //escreve mensagem no servidor.
00091                                 if(gravar_mensagem()==-1) 
00092                                         printf("Error!!!\n");
00093 
00094                                 break;
00095                         case 1: //le mensagem do banco de dados.
00096                                 ler_mensagens();
00097                                 break;
00098                         case 2://sai do serviço.
00099                                 printf("Tchau....\n");
00100                                 tchau = 1;
00101                                 return 0;
00102                                 break;
00103                         default: break;
00104                 }
00105         }while(1);      
00106 
00107         return 0;
00108 }
00109 
00110 #if 0   
00111 int envia_mensagem(){   
00112         int fp_tam, nro=0;
00113         char * fl_buff='\0';
00114         char * aux='\0';
00115         size_t result;
00116         
00117         printf("\nBuscnado mensagem...\n");
00118                         
00119         //configura abertura de arquivo para ser lido a nova mensagem.
00120         dtSft = fopen(FONT, "r");
00121                         
00122         if(dtSft == NULL){
00123                 printf("\nerror.");
00124                 return -1;
00125         }
00126                         
00127         // obtain file size:
00128         fseek (dtSft, 0 , SEEK_END);
00129         fp_tam = ftell (dtSft);
00130         rewind (dtSft);
00131 
00132         // allocate memory to contain the whole file:
00133         fl_buff = (char*) malloc (sizeof(char)*fp_tam);
00134         if (fl_buff == NULL) {fputs ("Memory error",stderr); return -1;}
00135 
00136         // copy the file into the buffer:
00137         result = fread (fl_buff,1,fp_tam,dtSft);
00138         if (result != fp_tam) {fputs ("Reading error",stderr); return -1;}
00139         // terminate
00140         fclose (dtSft);
00141 
00142         aux = strtok(fl_buff, ":");
00143         nro = atoi(aux);
00144                         
00145         while(aux !=NULL){
00146                 aux = strtok(NULL,"\n");
00147                 //printf("%d: %s  - old_id %d", nro, aux, old_id);
00148                 fflush(stdout);
00149                 
00150                 printf("\nNRO: %d NRO_SEND: %d\n", nro, id_send);
00151                 //monta mensagem e envia para o display
00152                 if(nro==id_send){
00153                         monta_pkt(aux);
00154                         id_send++; //proxima vez que for chamada pega a proxima mensagem.
00155                         if(id_send==999) id_send =0;
00156                         break;
00157                 }
00158                                 
00159                 aux = strtok(NULL, ":");
00160                 nro = atoi(aux);
00161                 if(aux==NULL) break;    //acabou o texto.
00162                                 
00163         }//enquanto arquivo aberto.
00164         
00165         return 0;
00166 }
00167 #endif
00168 
00176 int main(int argc, char *argv[])
00177 {
00178         id_send = 0;
00179         if (argc < 2) {
00180                 printf("Erro uso correto:\n") ;
00181                 printf("\n    %s <hostname> \n\n", argv[0]) ;
00182                 exit(1) ;
00183         }
00184 
00186         s1=socket(AF_INET, SOCK_STREAM, 0);
00187 
00188         if (s1<0) {
00189                  perror("opening stream socket");
00190                  exit(1);
00191         }
00192 
00193         hp = gethostbyname(argv[1]);
00194         if (hp == 0) {
00195                 fprintf(stderr,"%s: Unkown host\n",argv[1]);
00196                 exit(2);
00197         }
00198 
00199         server.sin_family = AF_INET;
00200         server.sin_port = htons(SFT_PORT);
00201         server.sin_addr = *((struct in_addr *)hp->h_addr);
00202         memset(&(server.sin_zero), '\0', 8);  // zero the rest of the struct 
00203 
00204 
00205         printf("\nConectando...\n") ;
00206         if (connect(s1, (struct sockaddr *)&server, sizeof server ) < 0) {
00207                 perror("connectando stream socket");
00208                 exit(1);
00209         }
00210 
00211         printf("\nConectado com sucesso...\n") ;
00212         id_stc =0; //inicaliza id das mensagens;
00213         
00214         //coloca o arquivo como ocupado.
00215         flag = 1;
00216         
00217         //flag para terminar o programa.
00218         tchau =0;
00219         //cria database
00220         if(cria_database()==-1) {
00221                 printf("\nerror!!!\n");
00222                 return 0;
00223         }
00224         
00225         system("clear");                        
00226         
00227         //menu();
00228         pthread_create(&tid1,NULL,menu, NULL);
00229         pthread_create(&tid2,NULL,gerencia, NULL);
00230 
00231         pthread_join(tid1, NULL);
00232     pthread_join(tid2, NULL);
00233 
00234 
00235         return 0;
00236         
00237 }
00238         
00239         
00240 int gravar_mensagem(void){
00241         char data[20];
00242 
00243         dtSft = fopen(FONT, "a");
00244         if(dtSft == NULL){
00245                 printf("\nerror\n");
00246                 return -1;
00247         }
00248 
00249         //coloca o arquivo como ocupado.
00250         flag = 1;
00251         
00252         //ADICIONA O ID A MENSAGEM
00253         sprintf(data, "%d: ", id_msg);
00254         fputs(data, dtSft);
00255         id_msg++;
00256 
00257         system("clear");                
00258         
00259         printf("Escreva a sua mensagem.");
00260         printf("\n:> ");
00261         //pega a informação do terminal.
00262         fgets_unlocked(msg, TAMMSG, stdin);//não pergunte como, mas funciona.... Não tente arrumar ;-)
00263         scanf("%[^\n]s", msg);
00264         setbuf(stdin, NULL);//tira o \0 do ultimo caracter. SUJEIRA
00265         
00266         //GRAVA A MENSAGEM DIGITADA.
00267         fputs (msg,dtSft);
00268         fputc ('\n',dtSft);
00269         
00270         fclose (dtSft);
00271         
00272         //libera o arquivo para ser usado por outro processo.
00273         system("clear");                
00274         flag = 0;
00275         return 0;
00276 }
00277         
00278 int ler_mensagens(void){
00279         char *base;
00280         size_t len= TAMMSG;
00281         
00282         flag = 1;
00283         dtSft = fopen(FONT, "r");
00284         if(dtSft == NULL){
00285                 printf("\nerror\n");
00286                 return -1;
00287         }
00288         
00289         system("clear");                
00290         printf("Mensagens:\n");
00291         printf("-----------------------------------------------------------------\n");
00292         
00293         base = malloc(TAMMSG);
00294 
00295         while (getline(&base, &len, dtSft) > 0){
00296                 printf("%s\n", base);
00297         }
00298         
00299         if (base)
00300                 free(base);
00301                 
00302         printf("-----------------------------------------------------------------\n\n\n\n");
00303         fclose(dtSft);
00304         
00305         flag = 0;
00306         return 0;
00307 }       
00308         
00309 
00315 int monta_pkt(char *aux){
00316         struct sft_hdr sf;
00317         int len, resp;
00318         
00319         //ID    
00320         sprintf(sf.id, "%03d", id_stc);
00321         id_stc++;
00322         if (id_stc==999) id_stc = 0;
00323         
00324         //comando
00325         //sprintf(sf->cmd, "%02d", CMD_MSG);
00326         strcpy(sf.cmd, "08");
00327                 
00328         //more fragments
00329         sprintf(sf.mf, "0");
00330         
00331                 
00332         //nro_pkt
00333         sprintf(sf.nro_pkt, "00");
00334                 
00335         //tamanho do pacote
00336         len = strlen(aux);
00337         sprintf(sf.len, "%04d", len);
00338         
00339         //mensagem para o display
00340         sprintf(sf.buff_send, "%s", aux);
00341         
00342 
00343         resp = send_pkt_msg(&sf);
00344         
00345         //printf("... mensagem enviada com sucesso.\n");
00346         fflush(stdout);
00347 
00348         //se erro, envia o pacote novamente.Apenas 1 vez.
00349         if(resp== CMD_ERROR){
00350                         //se não esta aguardando um novo pacote.
00351                         resp = send_pkt_msg(&sf);
00352         }
00353         if(resp == CMD_STOP) return CMD_STOP;
00354         if(resp!= CMD_SEND_WAIT) return -1;
00355 
00356         return 0;
00357 }
00358 
00359 
00360 int send_pkt_msg(struct sft_hdr *sft){
00361         int rval, cmd;
00362         struct sft_hdr *rec;
00363         char id[3], cmd_s[3];
00364 
00365         //envia sctruct.
00366 //      printf("CMD %s\t", sft->cmd);
00367 //      printf("LEN %s\t", sft->len);
00368 //      printf("MF %s\t", sft->mf);
00369 //      printf("ID %s\t", sft->id);
00370 //      printf("NR_PKT %s\n", sft->nro_pkt);
00371 
00372                 //printf("Mensagem enviada:\n%s: %s  - old_id %s", sft->id, sft->buff_send, sft->len);
00373                 fflush(stdout);
00374 
00375         send(s1, (struct sft_hdr *)sft, sizeof(struct sft_hdr), 0);
00376 
00377         //limpa struct para novo pacote.
00378         bzero((struct sft_hdr *)sft, sizeof(struct sft_hdr));
00379 
00380         //espera resposta..
00381         rval = recv(s1, msg_rec, TAMMSG, 0) ;
00382         
00383         //carrega resposta no vetor de dados sft.
00384         rec = (struct sft_hdr *)msg_rec;
00385 
00386         sprintf(id, "%03d", id_stc);
00387 
00388         fflush(stdout);
00389 
00390         //if (strncmp(rec->id, id,3)!=0) return CMD_ERROR;      //não é o ID do pacote que foi enviado.
00391         strncpy(cmd_s, rec->cmd, 2);
00392         cmd_s[3]='\0';
00393         cmd = strtol(cmd_s, NULL, 0);
00394 
00395         return cmd;
00396 }
00397 
00398 
00399 void *gerencia(){       
00400         int fp_tam, old_id = 0, nro=0;
00401         char * fl_buff='\0';
00402         char * aux='\0';
00403         size_t result;
00404         
00405         while(1){
00406                 
00407                 //flag serve para informar se o arquivo não está sendo usado para escrita ou se está disponivel.
00408                 if(flag==0){
00409                 
00410                         //verifica se o ID foi alterado.
00411                         if(old_id!=id_msg){     
00412                         
00413 //                              printf("\nMensagem sendo lida.\n");
00414                                 
00415                                 //configura abertura de arquivo para ser lido a nova mensagem.
00416                                 old_id = id_msg; //grava o ID como o anterior.
00417                                 dtSft = fopen(FONT, "r");
00418                                 
00419                                 if(dtSft == NULL){
00420                                         printf("\nerror.");
00421                                         continue;
00422                                 }
00423                                 
00424                                 // obtain file size:
00425                                 fseek (dtSft, 0 , SEEK_END);
00426                                 fp_tam = ftell (dtSft);
00427                                 rewind (dtSft);
00428 
00429                                 // allocate memory to contain the whole file:
00430                                 fl_buff = (char*) malloc (sizeof(char)*fp_tam);
00431                                 if (fl_buff == NULL) {fputs ("Memory error",stderr); continue; /*return -1;*/}
00432 
00433                                 // copy the file into the buffer:
00434                                 result = fread (fl_buff,1,fp_tam,dtSft);
00435                                 if (result != fp_tam) {fputs ("Reading error",stderr); continue;/*return -1;*/}
00436                                 // terminate
00437                                 fclose (dtSft);
00438 
00439                                 aux = strtok(fl_buff, ":");
00440                                 
00441                                 while(aux !=NULL){
00442                                         nro = atoi(aux);
00443                                         aux = strtok(NULL,"\n");
00444                                         //printf("%d: %s  - old_id %d", nro, aux, old_id);
00445                                         fflush(stdout);
00446                                         
00447                                         //monta mensagem e envia para o display
00448                                         if(nro==(old_id-1)){
00449                                                 monta_pkt(aux);
00450                                                 break;
00451                                         }
00452                                         
00453                                         aux = strtok(NULL, ":");
00454                                         if(aux==NULL) break;    //acabou o texto.
00455                                         
00456                                 }//enquanto arquivo aberto.
00457                                 
00458                         }//flag ==1
00459         
00460                 
00461                 }//id's diferentes
00462                 
00463                 if(tchau) break;
00464         }
00465         
00466 }
00467