/*
** echoc.c -- the echo client for echos.c; demonstrates unix sockets
*/

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

#define SOCK_PATH "echo_socket"

chop (char str[])
{
  str[strlen(str)-1]=(char)0; //Remove newline from fgets().
  printf("The string: >%s< Length: %d.\n", str, strlen(str));
}

nullify(char str[])
{
  int i; 
  for(i=0;i<100;i++)
    str[i]=0;
}

int main(void)
{

  int s, t, len;
  struct sockaddr_un remote;
  char str[100];
  
  if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
    perror("socket");
    exit(1);
  }
  
  printf("Trying to connect...\n");
  
  remote.sun_family = AF_UNIX;
  strcpy(remote.sun_path, SOCK_PATH);
  len = strlen(remote.sun_path) + sizeof(remote.sun_family);
  if (connect(s, (struct sockaddr *)&remote, len) == -1) {
    perror("connect");
    exit(1);
  }
  
  printf("Connected.\n");
  
  while(!feof(stdin))
  {
    printf("> "); 
    nullify(str);
    fgets(str, 100, stdin); 

    chop(str);

    if(strlen(str)==0)
    {
      close(s);
      exit(EXIT_SUCCESS);  
    }

    if (send(s, str, strlen(str), 0) == -1) {
      perror("send");
      exit(1);
    }
    
    str[0]=0;
    if ((t=recv(s, str, 100, 0)) > 0) {
      str[t] = '\0';
      printf("echo> %s", str);
    } else {
      if (t < 0) perror("recv");
      else printf("Server closed connection\n");
      exit(1);
    }
  }
  
  close(s);
  
  return 0;
}