select函數實現非阻塞讀數據

#include <iostream>
#include <map>
#include <string.h>
#include <unistd.h>
#include <assert.h>
#include <queue>
#include <sys/types.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <sys/select.h>
#include <arpa/inet.h>
#include <assert.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
using namespace std;

#define TIME_OUT_TIME 1

int m_SocketFd = 0;

int Select()
{
    struct timeval timout;
    fd_set wset, rset, eset;
    int ret, maxfdp1;
    int m_TimeOut = 500;

    if (m_TimeOut == 0)
        return 1;

    maxfdp1 = m_SocketFd + 1;
    FD_ZERO(&rset);
    FD_ZERO(&eset);
    FD_SET(m_SocketFd, &rset);
    FD_SET(m_SocketFd, &eset);
    FD_ZERO(&wset);

    timout.tv_sec = m_TimeOut / 1000;
    timout.tv_usec = (m_TimeOut % 1000) * 1000;
    
    ret = select(maxfdp1, &rset, &wset, &eset, &timout);
    if (ret == 0)
    {
        return 0;
    }
    if (ret < 0)
    {
        printf("Select return error %d\n", ret);
        return -1;
    }
    else
    {
    }

    return 1;
}

int main(int argc,char *argv[])
{
    int sockfd,numbytes;
    char buf[BUFSIZ];
    struct sockaddr_in their_addr;
    printf("break!");
    while((sockfd = socket(AF_INET,SOCK_STREAM,0)) == -1);
    printf("We get the sockfd~\n");
    their_addr.sin_family = AF_INET;
    their_addr.sin_port = htons(56789);
    their_addr.sin_addr.s_addr=inet_addr("10.12.2.136");
    bzero(&(their_addr.sin_zero), 8);

    bool ret = false;
    unsigned long ul = 1;
    m_SocketFd = sockfd;
    ioctl(m_SocketFd, FIONBIO, &ul);

    if (connect(sockfd,(struct sockaddr*)&their_addr,sizeof(struct sockaddr)) == -1)
    {
        int error = -1, len;
        len = sizeof(int);

        timeval tm;
        fd_set set;

        tm.tv_sec = TIME_OUT_TIME;
        tm.tv_usec = 0;
        FD_ZERO(&set);
        FD_SET(m_SocketFd, &set);

        if (select(m_SocketFd + 1, NULL, &set, NULL, &tm) > 0)
        {
            getsockopt(m_SocketFd, SOL_SOCKET, SO_ERROR, &error, (socklen_t*)&len);
            if (error == 0)
                ret = true;
            else
                ret = false;
        }
        else
        {
            ret = false;
        }
    }
    else
    {
        ret = true;
    }

    if (ret == false)
    {
        printf("connect server failure\n");
        close(m_SocketFd);
        return 0;
    }
    
    printf("Get the Server~Cheers!\n");
    buf[1024]='\0';  
    while(1)
    {
        int ret = Select();
        if (ret > 0)
        {
            int numbytes=recv(sockfd,buf,BUFSIZ,0);  
            printf("received:%s\n",buf);  
        }
        else if (ret == 0)
        {
            printf("timeout\n");
        }
        else
        {
            printf("error\n");
            break;
        }

        sleep(1);
    }
    close(sockfd);
    return 0;
}


 

發佈了54 篇原創文章 · 獲贊 3 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章