C++ Socket网络编程 1.3版本 将服务端升级为非阻塞Select模型

根据上节所示,select函数的最后一个参数设置为了NULL,这表明此时的select函数是阻塞形式的。
因此,本节通过改造select函数的最后一个参数,使它成为非阻塞形式,以处理更多的逻辑业务。
select的定义:

select(
    _In_ int nfds,
    _Inout_opt_ fd_set FAR * readfds,
    _Inout_opt_ fd_set FAR * writefds,
    _Inout_opt_ fd_set FAR * exceptfds,
    _In_opt_ const struct timeval FAR * timeout
    );

最后一个参数是timeval变量,其定义如下: (一般)

/*
 * Structure used in select() call, taken from the BSD file sys/time.h.
 */
struct timeval {
        long    tv_sec;         /* seconds */
        long    tv_usec;        /* and microseconds */
};

timeval t = {0,0}; //select查询超时的时间 windows下的计时器 目前没有计算微秒 0表示select函数如果查询没有需要处理,立即返回
将这个参数传递到select中。这样就使得服务端在没有开启多线程的情况下,既能够处理多个客户端的网络通信,又能够处理自身的业务逻辑。

猜你喜欢

转载自blog.csdn.net/La745739773/article/details/89065799