linux connect 非阻塞模式编程

凡是接触过socket编程的,对connect函数一定不陌生。因为socket是面向连接的,所以在进行读写操作前我们首先要进行连接,而所谓连接也就是我们常说的三次握手,这个过程就是在connect函数中完成的。 
虽然connect函数本身不具备阻塞的功能,但是我们可以通过对socket进行设置和使用select函数可以设置阻塞时间的特性实现非阻塞。

为什么要非阻塞

第一,我们可以在connect时去做些别的事,毕竟三次握手需要在网络中往返多层次,我们没有必要一直在那里闲着。 
第二,这一点很重要,因为connect的超时时间在75秒到几分钟之间,显然不可能去让程序阻塞那么久。

怎样实现非阻塞

1. 设置socket
int oldOption = fcntl(sockfd, F_GETFL);
int newOption = oldOption | O_NONBLOCK;
//设置sockfd非阻塞
fcntl(sockfd, F_SETFL, newOption);
2. 执行connect
如果返回0,表示连接成功,这种情况一般在本机上连接时会出现(否则怎么可能那么快)
否则,查看error是否等于EINPROGRESS(表明正在进行连接中),如果不等于,则连接失败
int ret = connect(sockfd, (struct sockaddr*)&addr, sizeof(addr));
if(ret == 0)
{
    //连接成功
    fcntl(sockfd, F_SETFL, oldOption);
    return sockfd;
}
else if(errno != EINPROGRESS)
{
    //连接没有立即返回,此时errno若不是EINPROGRESS,表明错误
    perror("connect error != EINPROGRESS");
    return -1;
}
3. 使用select,如果没用过select可以去看看
用select对socket的读写进行监听
那么监听结果有四种可能
1. 可写(当连接成功后,sockfd就会处于可写状态,此时表示连接成功)
2. 可读可写(在出错后,sockfd会处于可读可写状态,但有一种特殊情况见第三条)
3. 可读可写(我们可以想象,在我们connect执行完到select开始监听的这段时间内,
    如果连接已经成功,并且服务端发送了数据,那么此时sockfd就是可读可写的,
    因此我们需要对这种情况特殊判断)
    说白了,在可读可写时,我们需要甄别此时是否已经连接成功,我们采用这种方案:
    再次执行connect,然后查看error是否等于EISCONN(表示已经连接到该套接字)。
4. 错误

if(FD_ISSET(sockfd, &writeFds))
{
    //可读可写有两种可能,一是连接错误,二是在连接后服务端已有数据传来
    if(FD_ISSET(sockfd, &readFds))
    {
        if(connect(sockfd, (struct sockaddr*)&addr, sizeof(addr)) != 0)
        {
            int error=0;
            socklen_t length = sizeof(errno);
            //调用getsockopt来获取并清除sockfd上的错误.
            if(getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &error, &length) < 0)
            {
                printf("get socket option failed\n");
                close(sockfd);
                return -1;
            }
            if(error != EISCONN)
            {
                perror("connect error != EISCONN");
                close(sockfd);
                return -1;
            }
        }
    }
    //此时已排除所有错误可能,表明连接成功
    fcntl(sockfd, F_SETFL, oldOption);
    return sockfd;
}
4. 恢复socket
因为我们只是需要将连接操作变为非阻塞,并不包括读写等,所以我们吃醋要将socket重新设置。
fcntl(sockfd, F_SETFL, oldOption);
End

到此,我们的非阻塞connect函数已经成功了。

代码

#include <stdio.h>
#include <pthread.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <time.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <string>
#include <errno.h>

//blokTimeMs表明非阻塞时的毫秒数,若值为-1表明阻塞
int connect(std::string ip, int port, int blockTimeMs = -1)
{
    struct sockaddr_in addr;
    bzero(&addr, sizeof(addr));

    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    inet_pton(AF_INET, ip.c_str(), &addr.sin_addr);

    int sockfd = socket(PF_INET, SOCK_STREAM, 0);

    //阻塞
    if(blockTimeMs == -1)
    {
        int ret = connect(sockfd, (struct sockaddr*)&addr, sizeof(addr));
        if(ret < 0)
        {
            perror("connectBloking");
            close(sockfd);
            return -1;
        }
        close(sockfd);
        return 1;
    }

    //非阻塞
    int oldOption = fcntl(sockfd, F_GETFL);
    int newOption = oldOption | O_NONBLOCK;

    //设置sockfd非阻塞
    fcntl(sockfd, F_SETFL, newOption);

    int ret = connect(sockfd, (struct sockaddr*)&addr, sizeof(addr));
    if(ret == 0)
    {
        //连接成功
        fcntl(sockfd, F_SETFL, oldOption);
        return sockfd;
    }
    else if(errno != EINPROGRESS)
    {
        //连接没有立即返回,此时errno若不是EINPROGRESS,表明错误
        perror("connect error != EINPROGRESS");
        return -1;
    }

    fd_set readFds;
    fd_set writeFds;
    struct timeval timeout;

    FD_ZERO(&readFds);
    FD_ZERO(&writeFds);

    FD_SET(sockfd, &writeFds);
    FD_SET(sockfd, &readFds);

    timeout.tv_sec = blockTimeMs/1000;
    timeout.tv_usec = (blockTimeMs%1000)*1000;

    ret = select(sockfd+1, &readFds, &writeFds, NULL, &timeout);
    if(ret <= 0)
    {
        perror("select timeout or error");
        close(sockfd);
        return -1;
    }

    if(FD_ISSET(sockfd, &writeFds))
    {
        //可读可写有两种可能,一是连接错误,二是在连接后服务端已有数据传来
        if(FD_ISSET(sockfd, &readFds))
        {
            if(connect(sockfd, (struct sockaddr*)&addr, sizeof(addr)) != 0)
            {
                int error=0;
                socklen_t length = sizeof(errno);
                //调用getsockopt来获取并清除sockfd上的错误.
                if(getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &error, &length) < 0)
                {
                    printf("get socket option failed\n");
                    close(sockfd);
                    return -1;
                }
                if(error != EISCONN)
                {
                    perror("connect error != EISCONN");
                    close(sockfd);
                    return -1;
                }
            }
        }
        //此时已排除所有错误可能,表明连接成功
        fcntl(sockfd, F_SETFL, oldOption);
        return sockfd;
    }
    else
    {
        perror("connect failed");
        close(sockfd);
        return -1;
    }
}
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
0
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值