/* udpclib.c
 * Example of client using UDP protocol: it prints the current time 
 * and sends it with a prefix to server, it receives back a message from server
 * and prints it out.  It uses a timeout when waiting for a message.
 * You may test if the timeout works by running this program when no
 * server is available, or by killing the server and seeing what the client
 * prints out. Example of call to this program:
 *    udpclib roma.cis.temple.edu 5555
 */

#include   <stdio.h>
#include   <sys/types.h>
#include   <sys/socket.h>
#include   <netdb.h>
#include   <netinet/in.h>
#include   <sys/time.h>

#define MAXBUF 2*1024
#define MAXWAIT 5
#define PREFIXSIZE 23

main(argc, argv)
     int	argc;
     char	*argv[];
{
  
  int    sockfd;
  struct sockaddr_in	serv_addr;
  struct hostent *hp;
  char   buffer[MAXBUF];
  long   tm;           /* time */
  fd_set read_template;
  struct timeval wait;
  int    nb;
  int    count = 0;
  
  if (argc < 3) {
    printf("\nUSE: udpclib servername serverport\n"); exit(1);}
  
  /*
   * Open a UDP socket (an Internet datagram socket).
   */
  
  if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
    perror("client: can't open datagram socket");exit(1);}
  
  /*
   * Fill in the structure "serv_addr" with the address of the
   * server that we want to communicate with.
   */
  
  if ((hp = gethostbyname(argv[1])) == 0) {
    perror("gethostbyname"); exit(1);}
  bzero((char *) &serv_addr, sizeof(serv_addr));
  serv_addr.sin_family      = AF_INET;
  bcopy((char *)hp->h_addr, (char *)&serv_addr.sin_addr, hp->h_length);
  serv_addr.sin_port        = htons(atoi(argv[2]));
  
  /* 
   * sending and receiving messages 
   */
  
  while (1) {
    time(&tm);
    printf("At client %d Current time is %s\n", getpid(), ctime(&tm));
    sprintf(buffer, "ID = %5d, N = %5d  ", getpid(), count++);
    strcpy(&buffer[PREFIXSIZE], ctime(&tm));
    if (sendto(sockfd, buffer, strlen(buffer)*sizeof(char), 0, 
	       (struct sockaddr *)&serv_addr, 
	       sizeof(serv_addr)) < 0) {
      perror("sendto"); exit(1);}
    wait.tv_sec = MAXWAIT;
    wait.tv_usec = 0;
    FD_ZERO(&read_template);
    FD_SET(sockfd, &read_template);
    if ((nb = select(FD_SETSIZE, &read_template, NULL,NULL, &wait)) 
	<= 0){
      printf("Timed out\n");}
    else if (FD_ISSET(sockfd, &read_template)) {
      if (read(sockfd, buffer, MAXBUF) < 0) {
	perror("read"); exit(1);}
      printf("At client %d Data from server %s\n", getpid(), buffer);}
    sleep(1);
  }
  
  close(sockfd);
  exit(0);
}




