美文网首页
socket非阻塞时读取当前connect的状态

socket非阻塞时读取当前connect的状态

作者: andy_tu | 来源:发表于2018-04-23 20:49 被阅读0次

SetSocketBlock(hSocket, 0);  设置socket为非阻塞模式

intSetSocketBlock(intfd,intblock)

{

    intflags =fcntl(fd,F_GETFL,0);

    flags = block ? (flags &~O_NONBLOCK) : (flags |O_NONBLOCK);

    fcntl(fd,F_SETFL, flags);

    fLog(FC_LOG_Major,"CCSInf:SetSocketOptForTcp, block=%d", block);

}

在connect 时返回会是非阻塞,返回都为-1 没有连接成功就返回了,这里就需要去监听连接状态,在一定时间里如果还是获取不到或者没有连接成功,设置超时时间。只有连接成功了才能继续后面的send  和recv 。

nConnectRet=connect(hSocket, (sockaddr*)&skAddr,sizeof(skAddr));

fd_setfdwrite;

    fd_setfdread;

    fd_setfdexcept;

    FD_ZERO(&fdwrite);

    FD_ZERO(&fdread);

    FD_ZERO(&fdexcept);

    FD_SET(fd,&fdwrite);

    FD_SET(fd,&fdread);

    FD_SET(fd,&fdexcept);

    __int64t1 =GetTickCount();

    __int64t2 = nTimeOut *1000;

    structtimevaltimeout;

    timeout.tv_sec=1;

    timeout.tv_usec=0;

    while(1)

    {

        intret =select(fd+1,&fdread,&fdwrite,&fdexcept,&timeout);

        if(ret == -1)

        {

            return-1;

        }

        if(ret >0)

        {

            if(FD_ISSET(fd,&fdread))

            {

                interror;

                socklen_tlen =sizeof(error);

                ret =getsockopt(fd,SOL_SOCKET,SO_ERROR, (char*)&error, &len);

                fLog(FC_LOG_Major,"CCSInf: socketCanReadWrite, fdread ret=%d", ret);

                if(ret <0)

                    return-1;

                return0;

            }

            elseif(FD_ISSET(fd,&fdwrite))

            {

                interror;

                socklen_tlen =sizeof(error);

                ret =getsockopt(fd,SOL_SOCKET,SO_ERROR, (char*)&error, &len);

                fLog(FC_LOG_Major,"CCSInf: socketCanReadWrite, fdwrite ret=%d", ret);

                if(ret <0)

                    return-1;

                return0;

            }

            elseif(FD_ISSET(fd,&fdexcept))

            {

                fLog(FC_LOG_Major,"CCSInf: socketCanReadWrite, fdexcept ret=%d", -1);

                return-1;

            }

        }

        fLog(FC_LOG_Major,"CCSInf: socketCanReadWrite, select ret=%d", ret);

        if((GetTickCount() - t1 > t2))break;

        Sleep(20);

    }

相关文章

网友评论

      本文标题:socket非阻塞时读取当前connect的状态

      本文链接:https://www.haomeiwen.com/subject/phcrlftx.html