// dummyClient.cc
//   - sends server a name and waits for greeting to return
//   - compile: g++ -o dummyClient dummyClient.cc -lsocket

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <iostream.h>

const int BUFF_SIZE = 8192;

main(int argc, char* argv[])
  {
  int sock;
  sockaddr_un address;
  char sSocketName[80];
  char sBuff[BUFF_SIZE];

  // make sure the right number of arguments was given ----------------
  if (argc < 3)
    {
    cout << "usage: dummyClient <socketname> <person name>" << endl;
    exit(1);
    }

  // get socket name and message text from command line ---------------
  strcpy(sSocketName, argv[1]);
  strcpy(sBuff, argv[2]);

  // create socket ------------------------------------------(create)--
  if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
    {
    perror("client error: can't create socket");
    exit(1);
    }

  // initialize address -----------------------------------------------
  address.sun_family = AF_UNIX;
  strcpy(address.sun_path, sSocketName);

  // connect to socket -------------------------------------(connect)--
  if (connect(sock, (sockaddr*) &address, sizeof(address)) < 0)
    {
    perror("client error: can't connect to socket");
    exit(1);
    }

  // send message ---------------------------------------------(send)--
  if (write(sock, sBuff, strlen(sBuff)+1) < 0)
    {
    perror("client error: can't write to socket");
    exit(1);
    }
  cout << "[client: sending message {" << sBuff << "}]" << endl;

  // read reply ---------------------------------------------(receive)--
  if (read(sock, sBuff, sizeof(sBuff)) < 0)
    {
    perror("client error: can't read from socket");
    exit(1);
    }
  close(sock);
  cout << "[client: received response: {" << sBuff << "}]" << endl;
  } // end main
