LIPH's C++ Codes
tcp.h
Go to the documentation of this file.
1#ifndef LIPH_NET_TCP_H_
2#define LIPH_NET_TCP_H_
3
4#include "liph/macros.h"
5
6#ifdef OS_UNIX
7
8#include <functional>
9#include <memory>
10#include <string>
11#include <vector>
12
13#include "liph/io/poll.h"
14#include "liph/net/socket.h"
15
16namespace liph::net {
17
18class tcp_connect {
19public:
20 tcp_connect(std::shared_ptr<socket> socket) : socket_(socket) {}
21
22 std::vector<uint8_t> read_buf_;
23 std::vector<uint8_t> write_buf_;
24 std::shared_ptr<socket> socket_;
25};
26
27class tcp_server {
28public:
29 // 构造函数,server被动打开,参数port默认为0,表明动态分配端口,构造函数失败抛出runtime_error
30 tcp_server(int port = 0, bool ipv6 = false);
31 tcp_server(const tcp_server&) = delete;
32 ~tcp_server() {}
33
34 int port() const { return port_; }
35
36 std::shared_ptr<socket> get_socket() const { return socket_; }
37
38 void run(std::function<void(tcp_connect&)> handle);
39
40private:
41 bool start_server();
42
43private:
44 bool ipv6_;
45 int port_;
46 std::shared_ptr<socket> socket_;
47 std::shared_ptr<io::Poll> poll_;
48};
49
50} // namespace liph::net
51
52#endif
53
54#endif // LIPH_NET_TCP_H_