int ConnectServer(int port_, string host_) { int ret = 0; int socket_client_fd_; struct sockaddr_in server_addr_;
cout << "StartConnect()" << endl; // Create the socket to connect the server and set socket is unblocked. socket_client_fd_ = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0); if (socket_client_fd_ < 0) { cout << "Connect to server failed." << endl; return-1; }
// Set connect mode and ip host. server_addr_.sin_family = AF_INET; server_addr_.sin_port = htons(port_); server_addr_.sin_addr.s_addr = inet_addr(host_.c_str());
// Trying to connect the server. int maxfd = 0; fd_set wset; fd_set rset; int error = 0; struct timeval timeout; socklen_t len; bool conncet_successful = false;
cout << "Trying to connect " << host_ << ":" << port_ << "..." << endl; ret = connect(socket_client_fd_, (struct sockaddr *)&server_addr_, sizeof(server_addr_)); if (ret < 0) { if (errno != EINPROGRESS) { cout << "Connect error. " << strerror(errno) << endl; return-1; } // Create the select to listen the unblock connect successful. // Set the select catch event param. maxfd = socket_client_fd_ + 1; FD_ZERO(&wset); FD_ZERO(&rset); FD_SET(socket_client_fd_, &wset); FD_SET(socket_client_fd_, &rset); timeout.tv_sec = 10; timeout.tv_usec = 0;
do { sleep(5); cout << "Trying to connect " << host_ << ":" << port_ << "..." << endl; ret = select(maxfd, &rset, &wset, NULL, &timeout); if (ret > 0) { // cout << "Select write/read ok ret = " << ret << endl; // Catch the socket read and write event. if (FD_ISSET(socket_client_fd_, &rset) || FD_ISSET(socket_client_fd_, &wset)) { // Get the fd num event. if (getsockopt(socket_client_fd_, SOL_SOCKET, SO_ERROR, &error, &len) < 0) { // LOG(ERROR) << "ERROR CODE : " << errno; // LOG(ERROR) << "ERROR MSG : " << strerror(errno); continue; } // When error is 0 then connect successful. if (error != 0) { // LOG(ERROR) << "Connect to server failed"; continue; } // Retry connect the server. connect(socket_client_fd_, (struct sockaddr *)&server_addr_, sizeof(server_addr_)); if (errno == EISCONN) { cout << "Connect to server ok" << endl; conncet_successful = true; return socket_client_fd_; } continue; } } else { // No select the socket read or write event change. cout << "ret = " << to_string(ret) << endl; cout << "select: " << strerror(errno) << endl; continue; } } while (!conncet_successful); } // Connect failed. return-1; }
int main(int argc, charconst *argv[]) { return0; }