服务器的文件描述符数量有限,因此需要一些手段来限制服务器的最大并发连接数。
需要这么做的原因是:
考虑一种情况:
某个时刻服务器文件描述符已经用完了,此时再来一个连接,将无法用描述符表示这个连接,也就无法关闭这个连接。在Reactor模式下,POLLIN
事件就会一直被触发(level trigger模式),就会进入busy loop,cpu 利用率将到达100%。
因此有必要设计一个策略,当服务器并发数目到达上限时,主动的拒接连接。
muduo使用的办法很巧妙:
1.准备一个空闲的描述符
2.当遇到上述情况时,先close掉这个空闲的文件描述符,这样就多出一个可用描述符
3.接收新的连接后就有文件描述符来表示这个连接了。
4.此时close掉这个描述符,就关掉了客户端连接
5.再次打开这个空闲的描述符。
如何在muduo中限制并发连接数,以echoserver为例,只需简单设置一个计数器和最大连接数限制即可。
diff examples/simple/echo/echo.h examples/maxconnection/echo.h -u
--- examples/simple/echo/echo.h 2016-09-29 21:46:12.946963506 +0800
+++ examples/maxconnection/echo.h 2016-06-21 16:09:03.366311441 +0800
@@ -6,20 +6,23 @@
// RFC 862
class EchoServer
{
- public:
- EchoServer(muduo::net::EventLoop* loop,
- const muduo::net::InetAddress& listenAddr);
+ public:
+ EchoServer(muduo::net::EventLoop* loop,
+ const muduo::net::InetAddress& listenAddr,
+ int maxConnections);
- void start(); // calls server_.start();
+ void start();
- private:
- void onConnection(const muduo::net::TcpConnectionPtr& conn);
+ private:
+ void onConnection(const muduo::net::TcpConnectionPtr& conn);
- void onMessage(const muduo::net::TcpConnectionPtr& conn,
- muduo::net::Buffer* buf,
- muduo::Timestamp time);
+ void onMessage(const muduo::net::TcpConnectionPtr& conn,
+ muduo::net::Buffer* buf,
+ muduo::Timestamp time);
- muduo::net::TcpServer server_;
+ muduo::net::TcpServer server_;
+ int numConnected_; // should be atomic_int
+ const int kMaxConnections_;
};
#endif // MUDUO_EXAMPLES_SIMPLE_ECHO_ECHO_H
测试结果如下:
./maxconnection_echo 3 #设置最大并发数3
在终端用nc
工具连接测试,结果如下,当超出限制后,将自动踢掉连接:
参考:
Linux多线程 服务端编程 使用muduo C++ 网络库