-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtcp_server.h
More file actions
executable file
·98 lines (84 loc) · 1.82 KB
/
Copy pathtcp_server.h
File metadata and controls
executable file
·98 lines (84 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#pragma once
#include <string>
#include <boost\asio.hpp>
#include <boost\bind.hpp>
#include <boost\shared_ptr.hpp>
#include <boost\enable_shared_from_this.hpp>
using namespace std;
using namespace boost::asio;
using namespace boost::asio::ip;
/*
* ServiceType需要满足以下需求
* class ServiceType
* {
* public:
* // 构造函数
* ServiceType(io_service & io);
*
* // 返回socket对象
* tcp::socket & get_socket();
*
* // callback 连接已经建立
* void start();
* };
*/
template <class ServiceType>
class tcp_server : public boost::enable_shared_from_this<tcp_server<ServiceType> >
{
public:
typedef tcp_server<ServiceType> this_type;
tcp_server(io_service & io) : io(io), ac(io)
{}
io_service & get_io_service()
{
return io;
}
// 监听端口
void start(const string & ip, unsigned short port)
{
address addr = address::from_string(ip);
tcp::endpoint ep(addr, port);
ac.open(tcp::v4());
ac.set_option(tcp::socket::reuse_address(true));
ac.bind(ep);
ac.listen();
}
void accept()
{
boost::shared_ptr<ServiceType> service(new ServiceType(io));
auto cb = boost::bind(&this_type::handle_accept, shared_from_this(), service, _1);
ac.async_accept(service->get_socket(), cb);
}
protected:
void handle_accept(boost::shared_ptr<ServiceType> & service, const boost::system::error_code & ec)
{
if (!ec)
{
// accept成功,继续发起异步accept
try
{
accept();
}
catch (std::exception &)
{
// 异常
return;
}
// 通知Service对象连接已经建立
service->start();
}
else if (ec == error::operation_aborted)
{
// 取消了
ac.close();
}
else
{
// 错误
cerr << "acceptor error: " << ec.message() << endl;
}
}
private:
io_service & io;
tcp::acceptor ac;
};