Boost.Asio c++ 网络编程翻译(23)
void on_connect() {
do_read();
}
void do_read() {
async_read(sock_, buffer(read_buffer_),
MEM_FN2(read_complete,_1,_2), MEM_FN2(on_read,_1,_2));
}
void on_read(const error_code & err, size_t bytes) {
if ( err) stop();
if ( !started() ) return;
std::string msg(read_buffer_, bytes);
if ( msg.find("clients") == 0) on_clients(msg);
else ...
}
void on_clients(const std::string & msg) {
std::string clients = msg.substr(8);
std::cout << username_ << ", new client list:" << clients ;
do_write("clients ok\n");
}
void start() {
...
do_read(); // first, we wait for client to login
}
void on_read(const error_code & err, size_t bytes) {
std::string msg(read_buffer_, bytes);
if ( msg.find("login ") == 0) on_login(msg);
else if ( msg.find("ping") == 0) on_ping();
else ... }
void on_login(const std::string & msg) {
std::istringstream in(msg);
in >> username_ >> username_;
do_write("login ok\n");
}
void do_write(const std::string & msg) {
std::copy(msg.begin(), msg.end(), write_buffer_);
sock_.async_write_some( buffer(write_buffer_, msg.size()),
MEM_FN2(on_write,_1,_2));
}
void on_write(const error_code & err, size_t bytes) {
do_read(); }
void start() {
...
on_new_client_event();
}
void on_new_client_event() {
std::ostringstream msg;
msg << "client count " << clients.size();
for ( array::const_iterator b = clients.begin(), e = clients.
end();
(*b)->do_write(msg.str());
}
void on_read(const error_code & err, size_t bytes) {
std::string msg(read_buffer_, bytes);
// basically here, we only acknowledge
// that our clients received our notifications
}
void do_write(const std::string & msg) {
std::copy(msg.begin(), msg.end(), write_buffer_);
sock_.async_write_some( buffer(write_buffer_, msg.size()),
MEM_FN2(on_write,_1,_2));
}
void on_write(const error_code & err, size_t bytes) {
do_read(); }
ip::tcp::acceptor acc(service, ip::tcp::endpoint(ip::tcp::v4(),
8001));
void handle_accept(talk_to_client::ptr client, const error_code & err)
{
client->start();
talk_to_client::ptr new_client = talk_to_client::new_();
acc.async_accept(new_client->sock(), bind(handle_accept,new_
client,_1));
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。