C connect函数是阻塞的,现要实现非阻塞式的connect。
int SocketClient::connectTimeOut(const int &connect_fd, const int &timeout,const sockaddr_in &server) { int error=-1, len; len = sizeof(int); timeval tm; fd_set set; unsigned long ul = 1; ioctl(connect_fd, FIONBIO, &ul); //设置为非阻塞模式 bool ret = false; if( connect(connect_fd, (struct sockaddr *)&server, sizeof(struct sockaddr)) == -1) { tm.tv_sec = timeout; tm.tv_usec = 0; FD_ZERO(&set); FD_SET(connect_fd, &set); if( select(connect_fd+1, NULL, &set, NULL, &tm) > 0) { getsockopt(connect_fd, SOL_SOCKET, SO_ERROR, &error, (socklen_t *)&len); if(error == 0) ret = true; else ret = false; } else ret = false; } else ret = true; ul = 0; ioctl(connect_fd, FIONBIO, &ul); //设置为阻塞模式 if(!ret){ close(connect_fd); // fprintf(stderr,"Connect server fail "); } return ret; }