-
Notifications
You must be signed in to change notification settings - Fork 1
/
frameWork.cpp
77 lines (66 loc) · 1.68 KB
/
frameWork.cpp
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
#include <iostream>
#include <vector>
#include <memory>
#include <asio.hpp>
using namespace std;
using namespace asio;
using namespace asio::ip;
class Session : public enable_shared_from_this<Session> {
public:
Session(tcp::socket socket) : socket_(move(socket)) {}
void start() {
doRead();
}
private:
void doRead() {
auto self(shared_from_this());
socket_.async_read_some(buffer(data_, max_length),
[this, self](error_code ec, size_t length) {
if (!ec) {
doWrite(length);
}
});
}
void doWrite(size_t length) {
auto self(shared_from_this());
async_write(socket_, buffer(data_, length),
[this, self](error_code ec, size_t /*length*/) {
if (!ec) {
doRead();
}
});
}
tcp::socket socket_;
enum { max_length = 1024 };
char data_[max_length];
};
class Server {
public:
Server(io_context& io_context, short port)
: acceptor_(io_context, tcp::endpoint(tcp::v4(), port)),
socket_(io_context) {
doAccept();
}
private:
void doAccept() {
acceptor_.async_accept(socket_,
[this](error_code ec) {
if (!ec) {
make_shared<Session>(move(socket_))->start();
}
doAccept();
});
}
tcp::acceptor acceptor_;
tcp::socket socket_;
};
int main() {
try {
io_context io_context;
Server server(io_context, 8080);
io_context.run();
} catch (exception& e) {
cerr << "Exception: " << e.what() << "\n";
}
return 0;
}