linux 非阻塞 connect 注意事项

bool EnableBlockSocket(bool bEnable)
{
	INT  nResult = -1;
	
	INT nOption = fcntl(m_nFD, F_GETFL, 0);

	if (nOption >= 0)
	{
		if (bEnable)
		{
			nOption &= ~O_NONBLOCK;
		}
		else
		{
			nOption |= O_NONBLOCK;
		}
		nResult = fcntl(m_nFD, F_SETFL, nOption);		
	}
	assert(nResult >= 0);

	return (nResult >= 0);
}

bool Connect(INT nTimeout/* = 30*/)
{
	bool bResult = FALSE;

    if (INVALID_SOCKET == m_nFD)
    {
        m_nFD = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

        if (INVALID_SOCKET == m_nFD)
        {
            LOG_ERROR("Fail to create socket:%s\n", strerror(errno));
            return bResult;
        }
    }

    //设置为非阻塞模式
    EnableBlockSocket(FALSE);

    struct sockaddr_in sa;

    bzero(&sa, sizeof(struct sockaddr_in));
    sa.sin_family = AF_INET;
    sa.sin_addr.s_addr = HTONL(m_nIP);
    sa.sin_port = HTONS(m_nPort);

    //建立连接
    bResult = (connect(m_nFD, (struct sockaddr*)&sa, sizeof(sa)) != SOCKET_ERROR);

    if (!bResult)
    {
        // 非阻塞模式返回未完成
        if (errno == EINPROGRESS)
        {
            LOG_DEBUG("unblock mode socket is connecting...\n");
          
            fd_set objFDSet;

            FD_ZERO(&objFDSet);
            FD_SET(m_nFD, &objFDSet);

            timeval tm;

            tm.tv_sec = nTimeout;
            tm.tv_usec = 0;

            //select后需要坚持错误码
            if (select(m_nFD + 1, NULL, &objFDSet, NULL, &tm) > 0
                && FD_ISSET(m_nFD, &objFDSet))
            {
                int nErr = 0;
                socklen_t len = sizeof(nErr);
                if (0 == getsockopt(m_nFD, SOL_SOCKET, SO_ERROR, &nErr, &len))
                {
                    if (0 == nErr)
                    {
                        bResult = true;
                    }
                    else
                    {
                        LOG_ERROR("Fail to connnect host:%s\n", strerror(nErr));
                    }
                }
            }
        }
        else
        {
            LOG_ERROR("Fail to connnect host:%s\n", strerror(errno));
        }
    }

    //恢复为阻塞模式
    EnableBlockSocket(TRUE);

	return bResult;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值