select 模型

void CSockTcp::OnRunThreadProc()
{

    if(InitTcp())
    {
        

        fd_set fdsocket; 

        FD_ZERO(&fdsocket);
        FD_SET(m_sockListen, &fdsocket);

        timeval tv;
        tv.tv_sec=0;
        tv.tv_usec=1000; // 等待5秒

        char szbuf[MAX_BUFFER_SIZE] = {0};

        while(m_bThreadRunFlag)
        {
            fd_set fdread = fdsocket;

            int ret = select(0, &fdread, NULL, NULL, &tv);

            if(0==ret) // timeout
            {
                continue;
            }

            if(ret > 0)
            {
                for(int i=0; i<fdsocket.fd_count; i++)
                {
                    if(FD_ISSET(fdsocket.fd_array[i], &fdread)) 
                    {
                        if(fdsocket.fd_array[i] == m_sockListen) 
                        {
                            if(fdsocket.fd_count < FD_SETSIZE)
                            {
                                SOCKADDR_IN addrRemote;
                                int len = sizeof(SOCKADDR_IN);

                                SOCKET sockClient = ::accept(fdsocket.fd_array[i], (SOCKADDR*)&addrRemote, &len);
                                FD_SET(sockClient, &fdsocket);
                            }
                            else
                            {
                                m_logSys.LogOut("连接数超过最大值!");
                                continue;
                            }
                        } // if
                        else
                        {
                            // 接受数据
                            ZeroMemory(szbuf,MAX_BUFFER_SIZE);
                            int nRecv= recv(fdsocket.fd_array[i], szbuf, MAX_BUFFER_SIZE, 0);

                            if(nRecv > 0)
                            {
                               // 
                               szbuf[nRecv]='\n';
                               m_logRun.LogOut(szbuf);
                           
                            }

                            if(nRecv == 0 || ( (nRecv == SOCKET_ERROR) && WSAGetLastError() == WSAECONNRESET ))
                            {
                                ::closesocket(fdsocket.fd_array[i]);
                                FD_CLR(fdsocket.fd_array[i], &fdsocket);
                            }
                        }
                    }
                }
            }// if
        }//while

        FD_ZERO(&fdsocket);

       

        if(INVALID_SOCKET != m_sockListen)
        {
            ::closesocket(m_sockListen);
            m_sockListen=INVALID_SOCKET;
        }

    }
}

你可能感兴趣的:(socket,null,buffer)