select()用于阻止Windows中的套接字

时间:2014-06-24 06:16:09

标签: windows sockets

void CSocket::WaitForConnetion()
{
    CSocket* pSocket = NULL;

    fd_set readfds;
    readfds.fd_count = 1; 
    readfds.fd_array[0] = m_hSocket;

    timeval timeout;
    ZeroMemory(&timeout, sizeof(timeout));
    timeout.tv_sec = 10;

    while(!g_bQuit)
    {
        int iSelect = select(NULL, &readfds, NULL, NULL, &timeout);

        if (iSelect == SOCKET_ERROR)
        {
            // error
            break;
        }
        else
        {
            if (iSelect == 0)
            {
                // timeout
            }
            else
            {
                assert(iSelect == 1);
                SOCKET new_sock = accept(m_hSocket, NULL, NULL);

                if (new_sock != INVALID_SOCKET)
                {
                    pSocket = new CSocketEx(new_sock);
                    // create a new thread to process the connection request with pSocket
                }
            }
            continue;
        }
}

您好,所有

CSocket是一个套接字包装器。

在我的程序中使用阻塞套接字,当我想要彻底退出时,调用accept函数将被阻止,所以我必须终止调用accept的线程。我想使用上面的select函数。但是选择经常是非阻塞的socket,在上述环境下使用阻塞套接字有什么问题或疑虑吗?

借助EJP的帮助。我修改了下面的代码。有错误吗?正如你所说,如果我通过关闭套接字句柄来使用方式,我必须将套接字句柄传递给另一个线程然后关闭它,对于不同线程中的操作符一个sokcet是否安全?

void CSocket::WaitForConnetion()
{
    CSocket* pSocket = NULL;

    timeval timeout;
    ZeroMemory(&timeout, sizeof(timeout));
    timeout.tv_sec = 10;

    while(!g_bQuit)
    {
        fd_set readfds;
        readfds.fd_count = 1; 
        readfds.fd_array[0] = m_hSocket;

        int iSelect = select(NULL, &readfds, NULL, NULL, &timeout);

        if (iSelect == SOCKET_ERROR)
        {
            // error
            break;
        }
        else
        {
            if (iSelect == 0)
            {
                // timeout
            }
            else
            {
                assert(iSelect == 1);
                SOCKET new_sock = accept(m_hSocket, NULL, NULL);

                if (new_sock != INVALID_SOCKET)
                {
                    pSocket = new CSocketEx(new_sock);
                    // create a new thread to process the connection request with pSocket
                }
            }
            continue;
        }
}

0 个答案:

没有答案