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
| #include <iostream> #include <boost/asio.hpp> #include <memory>
using namespace boost::asio; using namespace boost::asio::ip; using namespace std;
class Session : public std::enable_shared_from_this<Session>{ public: Session(tcp::socket socket) : socket_(std::move(socket)) {
} void Start(){ do_read(); } private: void do_read(){ auto self(shared_from_this()); socket_.async_read_some(buffer(data_, max_length),[this, self](boost::system::error_code err, std::size_t length){ if(!err){ do_write(length); } }); } void do_write(std::size_t length){ auto self(shared_from_this()); socket_.async_write_some(buffer(data_, length), [this, self](boost::system::error_code err, std::size_t length){ if(!err){ do_read(); } }); } tcp::socket socket_; enum {max_length = 1024}; char data_[max_length]; };
class Server{ public: Server(io_context &io_ctx, short port) : acceptor_(io_ctx, tcp::endpoint(tcp::v4(), port)) { do_accept(); } private: void do_accept(){ acceptor_.async_accept([this](boost::system::error_code err, tcp::socket socket){ if(!err){ std::make_shared<Session>(std::move(socket))->Start(); } do_accept(); }); } private: tcp::acceptor acceptor_; };
int main() { io_context io_ctx; Server s(io_ctx, 8989); io_ctx.run(); return 0; }
|