/*** TCP Client ***/

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define	SERVICE_NAME	"tcpinetd"
#define	PROTOCOL	"tcp"
#define	HOST_NAME	"localhost"

int	Connect()
{
int	SocketNumber;		/* Socket descripter */
struct	servent	*ServiceEntry;	/* service entry */
struct	hostent	*HostEntry;	/* host entry */
struct	sockaddr_in	sin;	/* Socket Entry */

/* Get Socket */

/******deamon*******/

HostEntry = gethostbyname("localhost");
  if(!HostEntry){
    printf("error:failed to serch the host\n");
    exit(1);
  }

/******deamon-ed******/

if(0 > (SocketNumber = (socket(AF_INET,SOCK_STREAM,0))))
	{
	printf("\7Cannot get Socket.\n");
	perror("\n");
	exit(1);
	}

/* Set protocol family name */
sin.sin_family = AF_INET;

/* Set Host Address */
bcopy(HostEntry->h_addr,&sin.sin_addr,HostEntry->h_length);

/* Set Port N.o. */
 sin.sin_port = 5683;  //ServiceEntry->s_port;

if(0 > connect(SocketNumber,(struct sockaddr *)(&sin),sizeof(sin)))
	{
	printf("\7Cannot Connect.\n");
	perror("\n");
	exit(1);
	}

return SocketNumber;
}

void	Disconnect(int SocketNumber)
{
close(SocketNumber);
}

void	SendData(int SocketNumber,char *line)
{
if(strlen(line) != write(SocketNumber,line,strlen(line)))
	{
	printf("\7Send Failed.\n");
	exit(1);
	}
}

int	RecvData(int SocketNumber,char *line)
{
int	i;

for(i = 0 ;;)
	{
	if(1 != read(SocketNumber,line + i,1))
		continue;
	else
		{
		i++;
		*(line + i) = (char)0;
	
		if(((char)('\n')) == *(line + i - 1))
			return i;
		}
	}
}

int	main()
{
int	Sock;
char	Key[256];
char	Data[256];
char	buff[256];

Sock = Connect();	/* Connect */
printf("Connected.\n");

for(;;)
	{
	char	*p;

	printf("Input Keyword = ");
	fflush(stdout);

	gets(Key);
	sprintf(buff,"%s=\n",Key);
	SendData(Sock,buff);		/* Send It ! */

	if(0 == strlen(Key))
		break;			/* If End Mark */

	/* ---- Waiting for Server response Here --- */

	(void)RecvData(Sock,buff);		/* Recv It ! */

	if((char *)NULL != (p = strchr(buff,'\n')))
		*p = (char)0;

	if((char *)NULL != (p = strchr(buff,'=')))
		p++;

	printf("Keyword = [%s] / Data = [%s]\n\n",Key,p);
	}

Disconnect(Sock);	/* Disconnect */
printf("Disocnnected.\n");
}