/* Verteilte Systeme - Programmieraufgabe Uebungsblatt 6
   Author: Stefan Schonger
   Date  : 06/01/99

   simple client to test the server
   It just takes (possibly several lines of) input and sends them to the
   server. It also displays all the messages from the server.
*/

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <strings.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define MAX_BUF 10000
#define CHOMP(x) { x[strlen(x)] = '\0'; }

int main(int argc, char *argv[]) {
  int sockfd;
  struct sockaddr_in servAddr;
  pid_t pid;
  
  char mesgBuf[MAX_BUF];
  char buf[MAX_BUF];
  int mesgSize;
  
  if( argc < 3 ) {
    printf("usage: %s serverAddr serverPort\n", argv[0]);
    return 1;
  }
  
  /* Open a UDP socket */
  if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0 )) < 0){
    perror("Can't open socket");
    exit(-1);
  }

  /* setup server address */
  memset((char *) &servAddr, 0, sizeof(struct sockaddr_in));
  servAddr.sin_family      = AF_INET;
  servAddr.sin_addr.s_addr = inet_addr( argv[1]);
  servAddr.sin_port        = htons( atoi(argv[2]) );
  
  
  pid = fork();
  if(pid == 0) {
    /* send */
    for(;;) { /* forever */
      mesgBuf[0] = '\0';
      
      /* read from stdin */
      puts("Type multi-line text to send to server and \nend with a line with a single \".\"");
      fgets(buf, MAX_BUF, stdin);
      buf[strlen(buf)-1] = 0;
      while( strcmp(buf, "." ) != 0 ) {
	strcat(buf, "\r\n");
	strcat(mesgBuf, buf);
	fgets(buf, MAX_BUF, stdin);

	buf[strlen(buf)-1] = 0;
      }
      mesgBuf[strlen(mesgBuf)-2]='\0'; /* cut last \r\n away */

      /* Send Packet */
      if( sendto(sockfd, mesgBuf, strlen(mesgBuf), 0, (struct sockaddr *)&servAddr, sizeof(servAddr)) == -1) {
	perror("sendto server error!");
	exit(-1);
      }
    }
  } else {
    /* receive */
    for(;;) {  /* forever */
      mesgSize = recvfrom(sockfd, mesgBuf, MAX_BUF, 0, 0, 0);
      printf(">>Received packet from %s (%s)\n", inet_ntoa(servAddr.sin_addr), mesgBuf);
    }
  }
  
  return 0;
}
