欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

linux 下建立异步链接

程序员文章站 2022-07-14 10:15:12
...
int32_t SockEndPoint::connect_server()
{
	struct sockaddr_in client_addr;
    int sock_ret = 0;
    bzero(&client_addr, sizeof(client_addr) );
    client_addr.sin_family = AF_INET;
    client_addr.sin_addr.s_addr = htons(INADDR_ANY);
    client_addr.sin_port = htons(0);    

    client_socket_ = socket( AF_INET, SOCK_STREAM, 0);
    if ( client_socket_ < 0)
    {
        LOGV(LL_ERROR, "Create Socket Failed!\n" );
        return -1;
    }
    /*
    if ( bind( client_socket_ , (struct sockaddr*)&client_addr, sizeof(client_addr)))
    {
        LOGV(LL_ERROR, "Client Bind Port Failed!\n" ); 
        return -2;
    }*/
    struct sockaddr_in server_addr;
    bzero(&server_addr, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    if (inet_aton(addr_.c_str() , &server_addr.sin_addr) == 0)
    {
        LOGV(LL_ERROR, "Server IP Address Error!\n" );
        return -3;
    }

    int flags = 0,error = 0;
    socklen_t len;
    flags = fcntl( client_socket_, F_GETFL, 0);
    fcntl(client_socket_, F_SETFL, flags | O_NONBLOCK);
	
    server_addr.sin_port = htons( port_ );
    socklen_t server_addr_length = sizeof(server_addr);
 
    if ( (sock_ret = connect(client_socket_, (struct sockaddr*)&server_addr, server_addr_length)) < 0)
    {
        if ( errno != EINPROGRESS )
            return -1;
    }
    if( sock_ret == 0 )
    {
        LOGV(LL_INFO, "local connect To %s:%d ok!\n", addr_.c_str() , port_ );
    }

    FD_ZERO(&rdfds);
    FD_SET( client_socket_ , &rdfds);
    wdfds = rdfds;
    struct timeval tv;
    tv.tv_sec = 5;
    tv.tv_usec = 0;

    sock_ret = select( client_socket_ + 1, &rdfds, &wdfds , NULL, &tv);
    if ( sock_ret <= 0 )
    {
        LOGV(LL_ERROR, "select error  or timeout !");
        close(client_socket_);
        return -1;
    }
    if (/* FD_ISSET(client_socket_, &rdfds) ||*/ FD_ISSET(client_socket_, &wdfds) )
    {
        if ( FD_ISSET(client_socket_, &rdfds) )
        {
            LOGV(LL_ERROR, "socket refuse !");
            close(client_socket_);
            return -1;
        }
        if ( getsockopt(client_socket_, SOL_SOCKET, SO_ERROR, &error, &len) != 0)
        {
            if ( error )
            {
                LOGV(LL_ERROR, "Can not connect To %s:%d refuse,error %d msg %s !\n", 
                     addr_.c_str() , port_, error, strerror(error) );
                return -4;
            }
        }
        else 
        {
            LOGV(LL_INFO, "connect To %s:%d ok!\n", addr_.c_str() , port_ );
            connect_status_ = 1;
        }
    }else
    {
        LOGV(LL_ERROR, "Can not connect To %s:%d timeout!\n", addr_.c_str() , port_ );
        close(client_socket_);
        return -1;
    }

    printf("trace %d %d\n", client_socket_, sock_ret );
    fcntl(client_socket_, F_SETFL, flags);
 
    return 0;
}