Menu

[r2120]: / framework / trunk / examples / aio / echo_server.cpp  Maximize  Restore  History

Download this file

124 lines (103 with data), 2.9 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
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#include <booster/shared_ptr.h>
#include <booster/enable_shared_from_this.h>
#include <booster/aio/io_service.h>
#include <booster/aio/buffer.h>
#include <booster/aio/endpoint.h>
#include <booster/aio/acceptor.h>
#include <booster/aio/stream_socket.h>
#include <iostream>
#include <functional>
class echo_session : public booster::enable_shared_from_this<echo_session> {
public:
echo_session(booster::aio::io_service &s) : socket_(s)
{
}
void run()
{
socket_.async_read_some(
booster::aio::buffer(buffer_,sizeof(buffer_)),
std::bind(&echo_session::on_read,shared_from_this(),
std::placeholders::_1,
std::placeholders::_2));
}
void on_read(booster::system::error_code const &e,size_t tr)
{
if(e) return;
socket_.async_write(booster::aio::buffer(buffer_,tr),
std::bind(&echo_session::on_written,shared_from_this(),std::placeholders::_1));
}
void on_written(booster::system::error_code const &e)
{
if(e) return;
run();
}
private:
friend class echo_acceptor;
char buffer_[1024];
booster::aio::stream_socket socket_;
};
class stop_service {
public:
stop_service(booster::aio::io_service &srv) : stdin_(srv)
{
stdin_.attach(0);
}
void run()
{
stdin_.on_readable(std::bind(&stop_service::on_input,this));
}
void on_input()
{
stdin_.get_io_service().stop();
}
private:
booster::aio::basic_io_device stdin_;
};
class echo_acceptor {
public:
echo_acceptor(booster::aio::io_service &srv) : acceptor_(srv)
{
booster::aio::endpoint ep("0.0.0.0",8080);
acceptor_.open(ep.family());
acceptor_.bind(ep);
acceptor_.listen(10);
}
void run()
{
new_session_.reset(new echo_session(acceptor_.get_io_service()));
acceptor_.async_accept(new_session_->socket_,
std::bind(&echo_acceptor::on_accepted,this,std::placeholders::_1));
}
void on_accepted(booster::system::error_code const &e)
{
if(e) {
std::cout << e.message() << std::endl;
run();
}
else {
new_session_->run();
run();
}
}
private:
booster::aio::acceptor acceptor_;
booster::shared_ptr<echo_session> new_session_;
};
int main()
{
try {
booster::aio::io_service srv;
echo_acceptor acc(srv);
acc.run();
#if !defined(_WIN32) && !defined(__CYGWIN__)
stop_service stop(srv);
stop.run();
std::cout << "Press any key to stop" << std::endl;
#endif
srv.run();
}
catch(std::exception const &e) {
std::cerr<<e.what()<<std::endl;
}
}
// vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
MongoDB Logo MongoDB