#include   <sys/stat.h>     
#include   <sys/types.h>     
#include   <sys/socket.h>     
#include   <stdio.h>     
#include   <malloc.h>     
#include   <netdb.h>     
#include   <fcntl.h>  
#include   <unistd.h>  
#include   <netinet/in.h>  
#include   <arpa/inet.h>  

#define BUF_SIZE 1024

#define    RES_LENGTH  10240 

static int client_fd=0;
static int client_connect_flag = -1;
static char server_ip[16];
static short server_port;

int     connect_socket(char * server,int serverPort);  
int     send_msg(int sockfd,char * sendBuff);  
char *  recv_msg(int sockfd);  
int     close_socket(int sockfd);  

int init_socketfd()
{
	int sockfd = -1;
	
	if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0){  
      		herror("Init socket error!");  
	}  

	return sockfd;	 
}

void tcp_init_client_fd()
{
	client_fd = init_socketfd();
	
}

void tcp_connect_server(char *ip, u_short port)
{
	tcp_init_client_fd();

	strcpy(server_ip, ip);
	server_port = port;
	client_connect_flag = connect_socket(ip, port);
}

int is_tcp_connected()
{
	return client_connect_flag;	
}

/* * ********************************************************/  
int    connect_socket(char * server,int serverPort)
{  
    struct    sockaddr_in    addr;  
    struct    hostent        * phost;  

    bzero(&addr,sizeof(addr));  
    addr.sin_family = AF_INET;  
    addr.sin_port = htons(serverPort);  
    addr.sin_addr.s_addr = inet_addr(server); 
      
    if(addr.sin_addr.s_addr == INADDR_NONE){
        phost = (struct hostent*)gethostbyname(server);  
        if(phost==NULL){  
            herror("Init socket s_addr error!");  
            return -1;  
        }  
        addr.sin_addr.s_addr =((struct in_addr*)phost->h_addr)->s_addr;  
    }  
    if(connect(client_fd,(struct sockaddr*)&addr, sizeof(addr))<0)  
    {  
      //  perror("Connect server fail!");  
        return -1; //0表示成功，-1表示失败  
    }  
    else  
        return 0;  
}  



int tcp_send_msg( u_char *sendbuf, short len)  
{  
	int sendSize=0;  

	if((sendSize=send(client_fd,sendbuf,len,MSG_NOSIGNAL))<=0){  
		close_socket(client_fd);
		herror("Send msg error!");  
		return -1;  
	} 

	return sendSize;  
}  

int tcp_recv_msg(u_char *recvbuf)
{  
	int  recLenth=0;  

	if(( recLenth=recv(client_fd,recvbuf, BUF_SIZE,0))==-1 )  
	{
		close_socket(client_fd);
	  	return -1; 
	}  
       if( recLenth>0)
		recvbuf[recLenth] = 0;   
	return recLenth;  
}  

int tcp_check_connection()
{
	//if(client_connect_flag == -1)
	//	connect_socket(server_ip, server_port);

	return client_connect_flag;
}

/************************************************** 
 *关闭连接 
 * **********************************************/  
int close_socket(int sockfd)  
{  
	client_connect_flag = -1;
	close(sockfd);  

	smcli_connection_is_broken();

	return 0;  
}  
