/*** TCP Client ***/

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdlib.h>

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

int	Connect()
{
int	SocketNumber;		
struct	servent	*ServiceEntry;	
struct	hostent	*HostEntry;	
struct	sockaddr_in	sin;	






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


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


sin.sin_family = AF_INET;


bcopy(HostEntry->h_addr,&sin.sin_addr,HostEntry->h_length);


 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();	
printf("Connected.\n");

for(;;)
	{
	char	*p;

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

	gets(Key);
	sprintf(buff,"%s=\n",Key);
	SendData(Sock,buff);		

	if(0 == strlen(Key))
		break;			



	(void)RecvData(Sock,buff);	

	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);	
printf("Disocnnected.\n");
}