void read_request() {
if ( sock_.available())
}
already_read_ += sock_.read_some(
buffer(buff_ + already_read_, max_msg - already_read_));
void process_request() {
bool found_enter = std::find(buff_, buff_ + already_read_, ‘\n‘)
< buff_ + already_read_;
if ( !found_enter)
return; // message is not full
size_t pos = std::find(buff_, buff_ + already_read_, ‘\n‘) -
buff_;
std::string msg(buff_, pos);
...
if ( msg.find("login ") == 0) on_login(msg);
else if ( msg.find("ping") == 0) on_ping();
else ...
}
typedef std::vector<client_ptr> array;
array clients;
array notify;
std::string notify_msg;
void on_new_client() {
// on a new client, we notify all clients of this event
notify = clients;
std::ostringstream msg;
msg << "client count " << clients.size();
notify_msg = msg.str();
notify_clients();
}
void notify_clients() {
for ( array::const_iterator b = notify.begin(), e = notify.end();
b != e; ++b) {
(*b)->sock_.write_some(notify_msg);
}
}
void accept_thread() {
ip::tcp::acceptor acceptor(service, ip::tcp::endpoint(ip::tcp:
:v4(),8001));
while ( true) {
client_ptr new_( new talk_to_client);
acceptor.accept(new_->sock());
boost::recursive_mutex::scoped_lock lk(cs);
clients.push_back(new_);
} }
struct talk_to_client : boost::enable_shared_from_this<talk_to_client>
{
...
void answer_to_client() {
try {
read_request();
process_request();
} catch ( boost::system::system_error&) {
stop(); }
} };
struct talk_to_client : boost::enable_shared_from_this<talk_to_client>
{
boost::recursive_mutex cs;
boost::recursive_mutex cs_ask;
bool in_process;
void answer_to_client() {
{ boost::recursive_mutex::scoped_lock lk(cs_ask);
if ( in_process)
return;
in_process = true;
}
{ boost::recursive_mutex::scoped_lock lk(cs);
try {
read_request();
process_request();}
catch ( boost::system::system_error&) {
stop();
}
}
{ boost::recursive_mutex::scoped_lock lk(cs_ask);
in_process = false;
}
} };
原文地址:http://blog.csdn.net/mmoaay/article/details/40889083