Boost.Asio c++ 网络编程翻译(18)
同步服务端
它不能使用单线程;等带一个新的client是一个堵塞操作,所以我们须要另外一个线程来处理已经存在的client。
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_);
} }
void handle_clients_thread() {
while ( true) {
boost::this_thread::sleep( millisec(1));
boost::recursive_mutex::scoped_lock lk(cs);
for(array::iterator b = clients.begin(),e = clients.end(); b
!= e; ++b)
(*b)->answer_to_client();
// 删除已经超时的客户端
clients.erase(std::remove_if(clients.begin(), clients.end(),
boost::bind(&talk_to_client::timed_out,_1)),
clients.end());
}
}
int main(int argc, char* argv[]) {
boost::thread_group threads;
threads.create_thread(accept_thread);
threads.create_thread(handle_clients_thread);
threads.join_all();
}
typedef boost::shared_ptr<talk_to_client> client_ptr;
typedef std::vector<client_ptr> array;
array clients;
boost::recursive_mutex cs; // 用线程安全的方式訪问客户端数组
struct talk_to_client : boost::enable_shared_from_this<talk_to_client>
{
talk_to_client() { ... }
std::string username() const { return username_; }
void answer_to_client() {
try {
read_request();
process_request();
} catch ( boost::system::system_error&) {
stop(); }
if ( timed_out())
stop();
}
void set_clients_changed() { clients_changed_ = true; }
ip::tcp::socket & sock() { return sock_; }
bool timed_out() const {
ptime now = microsec_clock::local_time();
long long ms = (now - last_ping).total_milliseconds();
return ms > 5000 ;
}
void stop() {
boost::system::error_code err; sock_.close(err);
}
void read_request() {
if ( sock_.available())
read_)); }
... private:
already_read_ += sock_.read_some(
buffer(buff_ + already_read_, max_msg - already_
// ... same as in Synchronous Client
bool clients_changed_;
ptime last_ping;
};
它仅仅有在存在有效数据的情况才读取,这种话,服务端永远不会堵塞:
void process_request() {
bool found_enter = std::find(buff_, buff_ + already_read_, '\n')
< buff_ + already_read_;
if ( !found_enter)
return; // message is not full
// process the msg
last_ping = microsec_clock::local_time();
size_t pos = std::find(buff_, buff_ + already_read_, '\n') -
buff_;
std::string msg(buff_, pos);
std::copy(buff_ + already_read_, buff_ + max_msg, buff_);
already_read_ -= pos + 1;
if ( msg.find("login ") == 0) on_login(msg);
else if ( msg.find("ping") == 0) on_ping();
else if ( msg.find("ask_clients") == 0) on_clients();
else std::cerr << "invalid msg " << msg << std::endl;
}
void on_login(const std::string & msg) {
std::istringstream in(msg);
in >> username_ >> username_;
write("login ok\n");
update_clients_changed();
}
void on_ping() {
write(clients_changed_ ? "ping client_list_changed\n" : "ping
ok\n");
clients_changed_ = false;
}
void on_clients() {
std::string msg;
{ boost::recursive_mutex::scoped_lock lk(cs);
for( array::const_iterator b = clients.begin(), e = clients.
end() ;
b != e; ++b)
msg += (*b)->username() + " ";
}
write("clients " + msg + "\n");
}
void write(const std::string & msg) { sock_.write_some(buffer(msg)); }
Boost.Asio c++ 网络编程翻译(18)的更多相关文章
- Boost.Asio c++ 网络编程翻译(20)
异步服务端 这个图表是相当复杂的:从Boost.Asio出来你能够看到4个箭头指向on_accept.on_read,on_write和on_check_ping. 着也就意味着你永远不知道哪个异步调 ...
- Boost.Asio c++ 网络编程翻译(14)
保持活动 假如,你须要做以下的操作: io_service service; ip::tcp::socket sock(service); char buff[512]; ... read(sock, ...
- Boost.Asio c++ 网络编程翻译(26)
Boost.Asio-其他特性 这章我们讲了解一些Boost.Asio不那么为人所知的特性.标准的stream和streambuf对象有时候会更难用一些,但正如你所见.它们也有它们的益处.最后,你会看 ...
- Boost.Asio c++ 网络编程翻译(11)
*_at方法 这些方法在一个流上面做随机存取操作.你来指定read和write操作从什么地方開始(offset): async_read_at(stream, offset, buffer [, co ...
- Boost.Asio c++ 网络编程翻译(21)
同步VS异步 Boost.Asio的作者做了一个非常惊艳的工作:它能够让你在同步和异步中自由选择,从而更好的适应你的应用. 在之前的章节中,我们学习了每种类型应用的框架,比方同步client,同步服务 ...
- Boost.Asio c++ 网络编程翻译(16)
TCP异步服务端 核心功能和同步服务端的功能类似,例如以下: class talk_to_client : public boost::enable_shared_from_this<talk_ ...
- Boost.Asio c++ 网络编程翻译(10)
read/write方法 这些方法对一个流进行读写操作(能够是套接字,或者其它表现的像流的类): async_read(stream, buffer [, completion],handler):这 ...
- boost.asio系列——socket编程
asio的主要用途还是用于socket编程,本文就以一个tcp的daytimer服务为例简单的演示一下如何实现同步和异步的tcp socket编程. 客户端 客户端的代码如下: #include &l ...
- 使用boost.asio实现网络通讯
#include <boost/asio.hpp> #define USING_SSL //是否加密 #ifdef USING_SSL #include <boost/asio/ss ...
随机推荐
- Android Studio安装踩坑
title: Android Studio安装踩坑 date: 2018-09-07 19:31:32 updated: tags: [Android,Android Studio,坑] descri ...
- 【Shell】使用shell打印菜单,一键安装Web应用
问题描述: [解答] [root@A04-Test- scripts]# more menu.sh #!/bin/bash echo "1.[install lamp]" echo ...
- 03008_ServletContext
1.什么是ServletContext? (1)ServletContext代表是一个web应用的环境(上下文)对象,ServletContext对象 内部封装是该web应用的信息,Servle ...
- luogu1578 奶牛浴场 枚举点最大子矩阵
建议看看王知昆dalao的论文,讲得很好 #include <algorithm> #include <iostream> #include <cstring> # ...
- debug环境下打印
#ifdef DEBUG # define NSLog(...) NSLog(__VA_ARGS__) #else # define NSLog(...) {} #endif
- 【POJ 2585】Window Pains 拓扑排序
Description . . . and so on . . . Unfortunately, Boudreaux's computer is very unreliable and crashes ...
- Balanced Lineup(ST)
描述 For the daily milking, Farmer John's N cows (1 ≤ N ≤ 50,000) always line up in the same order. On ...
- MacPorts的安装和使用
1.安装 MacPorts的官方网站:http://www.macports.org/install.php 有dmg安装和源代码安装两种方式,下载dmg格式一步步安装即可 2.使用 更新ports ...
- IE7中a标签包含img,点击img,链接失效的bug
在做列表时,我们经常会这样写: <ul class="works-list"> <li> <a href=""> <d ...
- HDU——4162Shape Number(字符串的最小表示)
Shape Number Time Limit: 24000/12000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) T ...