Socket 非阻塞connect编程(源码)

linux 客户端 Socket 非阻塞connect编程(源码)

linux 客户端 Socket 非阻塞connect编程(源码)
非阻塞connect完整代码综合如下:
int main(int argc, char** argv)
{
int sockfd, recvbytes,res,flags,error,n;
socklen_t len;
fd_set rset,wset;
struct timeval tval;
tval.tv_sec = 0;
tval.tv_usec = 300000;
struct sockaddr_in serv_addr;
char* sendData = "1234567890";//发送字符串
char buf[1024] = "\0"; //接收buffer
//创建socket描述符
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("socket create failed");
return 1;
}

serv_addr.sin_family=AF_INET;
serv_addr.sin_port=htons(9999);
serv_addr.sin_addr.s_addr = inet_addr("58.31.231.255");
bzero(&(serv_addr.sin_zero),8);
flags = fcntl(sockfd,F_GETFL,0);
fcntl(sockfd,F_SETFL,flags|O_NONBLOCK);//设置为非阻塞

if ( (res = connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr)) )< 0)
{
if(errno != EINPROGRESS)
{
return 1;
}

}
//如果server与client在同一主机上,有些环境socket设为非阻塞会返回 0
if(0 == res) goto done;
FD_ZERO(&rset);
FD_SET(sockfd,&rset);
wset = rset;
if( ( res = select(sockfd+1, NULL, &wset, NULL,&tval) ) <= 0)
{
perror("connect time out\n");
close(sockfd);
return 1;
}
else
{
len = sizeof(error);
getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &error, &len);
if (error)
{
fprintf(stderr, "Error in connection() %d - %s\n", error, strerror(error));
return 1;
}
}
done:
if ( (n = send(sockfd, sendData, strlen(sendData),0) ) ==-1 )
{

perror("send error!");
close(sockfd);
return 1;
}
if( ( n = select(sockfd+1,&rset,NULL, NULL,&tval)) <= 0 )//rset没有使用过,不用重新置为sockfd
{
perror("receive time out or connect error");
close(sockfd);
return -1;
}
if ((recvbytes=recv(sockfd, buf, 1024, 0)) ==-1)
{
perror("recv error!");
close(sockfd);
return 1;
}
printf("receive num %d\n",recvbytes);
printf("%s\n",buf);

}

你可能感兴趣的:(connect)