37_重写fd_set

fd_size在linux系统中最多支持1024,我们可以在windows系统中直接定义宏来确定fd_size的大小,但是linux系统中不能定义宏来确定fd_size的值,因为fd_set在linux系统中的存储和windows系统是不一样的,是通过位确定的。

CELLFDSet.hpp

#ifndef _CELL_FDSET_HPP_
#define _CELL_FDSET_HPP_

#include"CELL.hpp"

#define CELL_MAX_FD 10240

class CELLFDSet
{
public:
    CELLFDSet()
    {
        int nSocketNum = CELL_MAX_FD;
#ifdef _WIN32
        _nfdSize = sizeof(u_int) + (sizeof(SOCKET)*nSocketNum);
#else
        _nfdSize = nSocketNum / (8 * sizeof(char));       //linux下的fd_set设置
#endif // _WIN32
        _pfdset = (fd_set *)new char[_nfdSize];
        memset(_pfdset, 0, _nfdSize);
    }

    ~CELLFDSet()
    {
        if (_pfdset)
        {
            delete[] _pfdset;
            _pfdset = nullptr;
        }
    }

    inline void add(SOCKET s)
    {
#ifdef _WIN32
        FD_SET(s, _pfdset);
#else
        if(s < CELL_MAX_FD)
        {
            FD_SET(s, _pfdset);
        }else{
            CELLLog_Error("CELLFDSet::add sock<%d>, CELL_MAX_FD<%d>",(int)s,CELL_MAX_FD);
        }
#endif // _WIN32
    }

    inline void del(SOCKET s)
    {
        FD_CLR(s, _pfdset);
    }

    inline void zero()
    {
#ifdef _WIN32
        FD_ZERO(_pfdset);
#else
        memset(_pfdset, 0, _nfdSize);
#endif // _WIN32
    }

    inline bool has(SOCKET s)
    {
        return FD_ISSET(s, _pfdset);
    }

    inline fd_set* fdset()
    {
        return _pfdset;
    }

    void copy(CELLFDSet& set)
    {
        memcpy(_pfdset, set.fdset(), set._nfdSize);
    }
private:
    fd_set * _pfdset = nullptr;
    size_t _nfdSize = 0;
};


#endif // !_CELL_FDSET_HPP_

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top