#define HOST_SERVER_IP "192.168.3.35"
#define HOST_PORT 9501
#define SLEEP_TIME 1
#define LOOP_TIME 3
#define DATA_SIZE 80
int judge_socket_exist()
{
int loop_time = ;
fd_set send_data_flag;
static int socket_fd = -;
while()
{
if (socket_fd <= )
{
socket_fd = socket(AF_INET, SOCK_DGRAM, );
loop_time++;
}
if (socket_fd > )
{
FD_ZERO(&send_data_flag);
FD_SET(socket_fd, &send_data_flag);
FD_SET(, &send_data_flag);
//check socket is effective
if (select(socket_fd+, NULL, &send_data_flag, NULL, ) > )
{
break;
}
else
{
socket_fd = socket(AF_INET, SOCK_DGRAM, );
loop_time++;
}
}
if (loop_time > LOOP_TIME)
{
return -;
}
sleep(SLEEP_TIME);
}
return socket_fd;
}
int gsh_post_client(const char* sn, const char* ip)
{
if (NULL == sn || NULL == ip)
{
return -;
}
int loop_time = ; //loop time of fail execute
int send_data_length = ; //length of sending data
int select_err = -; //flag of select function back value
int socket_fd = judge_socket_exist(); //set socket flag, socket not close
struct timeval select_wait = {, }; //select function wait time
char text[BUFSIZ];
char send_data_buffer[DATA_SIZE]; //buffer of sending data
struct sockaddr_in socket_addr; //socket address of server ip and port
fd_set send_data_flag; //select function send data flag
if (socket_fd <= )
{
fprintf(stderr, "establish socket fail");
return -;
}
//initialize socket data
bzero(&socket_addr, sizeof(socket_addr));
socket_addr.sin_family = AF_INET;
socket_addr.sin_port = htons(HOST_PORT);
inet_aton(HOST_SERVER_IP, &socket_addr.sin_addr);
//initialize request data
memset(&send_data_buffer, , sizeof(send_data_buffer));
strcat(send_data_buffer, "sn=");
strcat(send_data_buffer, sn);
strcat(send_data_buffer, "&ip=");
strcat(send_data_buffer, ip);
while() //for no-blocking
{
if (loop_time > LOOP_TIME)
{
fprintf(stderr, "send data fail\n");
return -;
}
FD_ZERO(&send_data_flag);
FD_SET(socket_fd, &send_data_flag);
FD_SET(, &send_data_flag);
select_err = select(socket_fd+, NULL, &send_data_flag, NULL, &select_wait);
if (select_err <= )
{
loop_time++;
}
else
{
if (FD_ISSET(socket_fd, &send_data_flag))
{
loop_time = ;
FD_CLR(socket_fd, &send_data_flag);
while(send_data_length < strlen(send_data_buffer))
{
send_data_length = sendto(socket_fd, send_data_buffer, strlen(send_data_buffer), , (struct sockaddr *)&socket_addr, sizeof(socket_addr));
if (send_data_length <= )
{
fprintf(stderr, "sending data fail\n");
return -;
}
if (loop_time > LOOP_TIME)
{
fprintf(stderr, "length of sending data shorten than data\n");
return -;
}
if (send_data_length < strlen(send_data_buffer))
{
loop_time++;
sleep(SLEEP_TIME);
}
}
recvfrom(socket_fd,text,sizeof(text), , NULL, NULL);
printf("%s", text);
break;
}
else
{
loop_time++;
}
}
sleep(SLEEP_TIME);
}
return ;
}