MSTL 1.4.0
A Modern C++ Library with extended functionality, web components, and utility libraries
载入中...
搜索中...
未找到
tcp_server.hpp
1#ifndef MSTL_NETWORK_TCP_TCP_SERVER_HPP__
2#define MSTL_NETWORK_TCP_TCP_SERVER_HPP__
5#include "MSTL/core/container/vector.hpp"
7#include "ssl_socket.hpp"
9
10class MSTL_API tcp_server {
11public:
12#ifdef MSTL_SUPPORT_OPENSSL__
13 using handle_sock_t = ssl_socket;
14#else
15 using handle_sock_t = tcp_socket;
16#endif
17
18 using client_handler_t = function<void(handle_sock_t)>;
19
20private:
21 tcp_socket server_socket_{};
22#ifdef MSTL_SUPPORT_OPENSSL__
23 ssl_context ssl_ctx_{};
24#endif
25
26 uint16_t port_;
27 int backlog_;
28 _MSTL atomic_bool running_{false};
29 vector<_MSTL thread> worker_threads_{};
30
31 client_handler_t client_handler_{};
32
33private:
34 void start_workers(int thread_count);
35 void accept_conns();
36
37public:
38 explicit tcp_server(uint16_t port, int backlog = 128);
39 ~tcp_server() { stop(); }
40
41#ifdef MSTL_SUPPORT_OPENSSL__
42 bool load_certificate(const string& cert_file, const string& key_file);
43#endif
44
45 void set_client_handler(client_handler_t handler) noexcept {
46 client_handler_ = _MSTL move(handler);
47 }
48 MSTL_NODISCARD const client_handler_t& client_handler() const noexcept {
49 return client_handler_;
50 }
51
52 MSTL_NODISCARD uint16_t port() const noexcept {
53 return port_;
54 }
55 MSTL_NODISCARD bool is_running() const noexcept {
56 return running_;
57 }
58
59 bool start(SOCKET_DOMAIN domain = SOCKET_DOMAIN::IPV4,
60 SOCKET_TYPE type = SOCKET_TYPE::STREAM,
61 SOCKET_PROTOCOL protocol = SOCKET_PROTOCOL::AUTO,
62 uint16_t thread_count = 5);
63
64 void stop() noexcept;
65};
66
68#endif // MSTL_NETWORK_TCP_TCP_SERVER_HPP__
MSTL原子类型完整实现
MSTL通用函数包装器
atomic< bool > atomic_bool
布尔原子类型
unsigned short uint16_t
16位无符号整数类型
#define _MSTL
全局命名空间MSTL前缀
#define MSTL_END_NAMESPACE__
结束全局命名空间MSTL
#define MSTL_BEGIN_NAMESPACE__
开始全局命名空间MSTL
constexpr Iterator2 move(Iterator1 first, Iterator1 last, Iterator2 result)
移动范围元素
MSTL线程支持