求助,板子连服务器一段时间后,往服务器发送数据过程,出现超时,和服务器重新创建连接,返回-1,perror:connection timed out ,板子重启后又好,过一段时间又出现这现象。
代码:
连接函数:
int ConnectServer()
{
struct sockaddr_in serv_addr;
int ret;
static int connect_times=0;//与服务器建立链接次数
printf("start connect server!\n");
connect_times++;
printf("connect_times=%d\n",connect_times);
printf("sockfd:%d\n",sockfd);
if(sockfd > 0)
{
close(sockfd);
sockfd=-1;
}
sockfd = CreatSocket();
if(sockfd < 0)
exit(-1);
bzero(&serv_addr, sizeof(struct sockaddr_in));
serv_addr.sin_family=AF_INET;
serv_addr.sin_port=htons(global.arg_config.ServerPort);
serv_addr.sin_addr.s_addr = inet_addr(global.arg_config.ServerIp);
ret = connect(sockfd, (struct sockaddr *)&serv_addr,sizeof(struct sockaddr));
if(ret < 0)
{
perror("connect server");
return -1;
}
printf("connect server OK!\n");
connect_server_flag=0;
return 0;
}
发送线程:
while(1)
{
if(connect_server_flag==1)
ConnectServer();
发送数据
}
接收线程:
while(!global.app_stop)
{
struct timeval timeout;
fd_set rfds;
int con_fd;
bzero(buffer,sizeof(buffer));
bzero(buf,sizeof(buf));
con_fd = sockfd;
if(con_fd<0)continue;
timeout.tv_sec=15;
timeout.tv_usec=0;
FD_ZERO(&rfds);
FD_SET(con_fd, &rfds);
while(connect_server_flag)
{
printf("not connect yet\n");
continue;
}
ret = select(con_fd + 1, &rfds, NULL, NULL, &timeout);
printf("select ret = %d\n",ret);
if(ret < 0){
ErrDebug("select error");
sleep(1);
continue;
}else if (ret == 0) {
continue;
}else{
if (FD_ISSET(con_fd, &rfds))
{
ret = recv(con_fd, buf, sizeof(buf), 0);
if(ret > 0)
{
analy(buf);
}
else
{
if(ret<0 && (errno == EAGAIN||errno == EWOULDBLOCK||errno == EINTR) )
continue;
else
{
close(sockfd);
connect_server_flag=1;
}
}
} |