/* 
 * Example of slave using TCP protocol.
 * Reference: W. Richard Stevens. "UNIX Network Programming". 
 *            Prentice Hall Software Series. 1990.
 *            Chapter 6: Berkeley Sockets.
 */

#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <unistd.h>

#define REQ_SIZE      100
#define RES_SIZE      100
#define SERV_TCP_PORT 1024

/***********************************************/
/* Function: main */
/**********************************************/
int main(int argc, char *argv[]){
  int sockfd, newsockfd, clilen;
  struct sockaddr_in cli_addr, serv_addr;
  char request[REQ_SIZE];
  char response[RES_SIZE];    
    
  /*
   * Open a TCP socket (an Internet stream socket).
   */    
  if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
    fprintf(stderr,"slave: can't open stream socket\n");  
  }
  /* 
   * Bind our local address so that the master can send to us.
   */    
  bzero((char *) &serv_addr, sizeof(serv_addr));
  serv_addr.sin_family = AF_INET;
  serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
  serv_addr.sin_port = htons(SERV_TCP_PORT);    
  if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0){
    fprintf(stderr,"slave: can't bind local address\n");
  }    
  listen(sockfd, 5);    
  /* 
   * Wait for a connection from the master process. 
   */
  clilen = sizeof(cli_addr);
  printf("slave: ready to accept connection request\n");
  newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);        
  if (newsockfd < 0){
    fprintf(stderr,"slave: accept error\n");
  }
  printf("slave: ready to receive request\n");
  /* 
   * Receive the request from the master.
   */     
  if (recv(newsockfd, (void *)request, REQ_SIZE, MSG_WAITALL|MSG_NOSIGNAL) < 0){
    fprintf(stderr,"slave: can't receive request\n");    
    close(newsockfd);
    exit(1);
  }
  printf("slave: request= %s \n",request);
  /* 
   * Process the request. 
   */	
  /*
   *  ...
   */
  /* 
   * Send the response to the master. 
   */
  strcpy(response,"teste");
  if (send(newsockfd, (void *)response, RES_SIZE, MSG_NOSIGNAL) < 0){
    fprintf(stderr,"slave: can't send response\n");    
    close(newsockfd);
    exit(1);
  }	    
  close(newsockfd);
  close(sockfd);
  exit(0);
}
     
     

 
