#include <stdio.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
main(int argc, char **argv)
{
  int sock, done = 0;
  struct sockaddr_in address;
  struct hostent *hp;
  
  if (argc < 2) {
    fprintf(stderr, "Usage: %s <servermachine>\n", argv[0]);
    exit(-1);
  }
  sock = socket(AF_INET, SOCK_STREAM, 0);
  hp = gethostbyname(argv[1]);
  address.sin_family = AF_INET;
  address.sin_port = htons(9001);
  memcpy((char *) &address.sin_addr, hp->h_addr, sizeof(address.sin_addr));
  if (connect(sock, (struct sockaddr *)&address, sizeof(struct sockaddr_in))) {
    perror("client");
    exit(-1);
  }
  while (!done) {
    int serverReady = 0, stdinReady = 0;
    fd_set ready;
    
    FD_ZERO(&ready);
    FD_SET(sock, &ready);
    FD_SET(0, &ready);
    if (select(sock+1, &ready, NULL, NULL, NULL) < 0) {
      perror("client");
    }
    if (FD_ISSET(sock, &ready)) serverReady = 1;
    if (FD_ISSET(0, &ready)) stdinReady = 1;
    if (serverReady) {
      char buf[1024];
      int bytes = read(sock, buf, 1024);
      
      if (bytes < 0) {
        perror("client");
      } else if (bytes > 0) {
        buf[bytes] = '\0';
        fprintf(stdout, "%s", buf);
      } else {
        fprintf(stderr, "Connection closed by server\n");
        done = 1;
      }
    }
    if (stdinReady) {
      char buf[1024];
      int bytes = read(0, buf, 1024);
      if (bytes < 0) {
        perror("client");
      } else if (bytes == 0) {
        done = 1;
      } else if (bytes > 0) {
        buf[bytes] = '\0';
        if (write(sock, buf, bytes) < 0) {
          perror("client");
        }
      }
    }
  }
  close(sock);
  exit(0);
}

