張沈鵬 電子科技大學(xué)大三 生物醫(yī)學(xué)工程
我的C++Blog
我的文學(xué)Blog
更新:2006.10 beta
參考:BOOST文檔
- -- 歡迎轉(zhuǎn)載,但請保留引用網(wǎng)址以獲得更新
1. 序言
現(xiàn)在學(xué)的東西很容易忘記,寫這篇文章的目的是能讓我在需要時快速找回當(dāng)時的感覺. Let's BOOST THE WORLD .
2. 編譯:VC2005注意
在 屬性->C/C++->預(yù)處理器->預(yù)處理定義 中加入
_CRT_SECURE_NO_DEPRECATE;
來屏蔽不必要的警告
3. Asio 網(wǎng)絡(luò)庫
Boost.Asio是利用當(dāng)代C++的先進(jìn)方法,跨平臺,異步I/O模型的C++網(wǎng)絡(luò)庫.
3.1. 網(wǎng)絡(luò)庫:VC2005注意
在 屬性->C/C++->命令行 中加入
-DBOOST_REGEX_NO_LIB
來防止自動連接.
3.2. 同步Timer
本章介紹asio如何在定時器上進(jìn)行阻塞等待(blocking wait).
實(shí)現(xiàn),我們包含必要的頭文件.
所有的asio類可以簡單的通過include "asio.hpp"來調(diào)用.
#include <iostream>
#include <boost/asio.hpp>
此外,這個示例用到了timer,我們還要包含Boost.Date_Time的頭文件來控制時間.
#include <boost/date_time/posix_time/posix_time.hpp>
使用asio至少需要一個boost::asio::io_service對象.該類提供了訪問I/O的功能.我們首先在main函數(shù)中聲明它.
int main()
{
boost::asio::io_service io;
下一步我們聲明boost::asio::deadline_timer對象.這個asio的核心類提供I/O的功能(這里更確切的說是定時功能),總是把一個io_service對象作為他的第一個構(gòu)造函數(shù),而第二個構(gòu)造函數(shù)的參數(shù)設(shè)定timer會在5秒后到時(expired).
boost::asio::deadline_timer t(io, boost::posix_time::seconds(5));
這個簡單的示例中我們演示了定時器上的一個阻塞等待.就是說,調(diào)用boost::asio::deadline_timer::wait()的在創(chuàng)建后5秒內(nèi)(注意:不是等待開始后),timer到時之前不會返回任何值.
一個deadline_timer只有兩種狀態(tài):到時,未到時.
如果boost::asio::deadline_timer::wait()在到時的timer對象上調(diào)用,會立即return.
t.wait();
最后,我們輸出理所當(dāng)然的"Hello, world!"來演示timer到時了.
std::cout << "Hello, world!\n";
return 0;
}
完整的代碼:
#include <iostream>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
int main()
{
boost::asio::io_service io;
boost::asio::deadline_timer t(io, boost::posix_time::seconds(5));
t.wait();
std::cout << "Hello, world!\n";
return 0;
}
3.3. 異步Timer
#include <iostream>
#include <asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
asio的異步函數(shù)會在一個異步操作完成后被回調(diào).這里我們定義了一個將被回調(diào)的函數(shù).
void print(const asio::error& /*e*/)
{
std::cout << "Hello, world!\n";
}
int main()
{
asio::io_service io;
asio::deadline_timer t(io, boost::posix_time::seconds(5));
這里我們調(diào)用asio::deadline_timer::async_wait()來異步等待
t.async_wait(print);
最后,我們必須調(diào)用asio::io_service::run().
asio庫只會調(diào)用那個正在運(yùn)行的asio::io_service::run()的回調(diào)函數(shù).
如果asio::io_service::run()不被調(diào)用,那么回調(diào)永遠(yuǎn)不會發(fā)生.
asio::io_service::run()會持續(xù)工作到點(diǎn),這里就是timer到時,回調(diào)完成.
別忘了在調(diào)用 asio::io_service::run()之前設(shè)置好io_service的任務(wù).比如,這里,如果我們忘記先調(diào)用asio::deadline_timer::async_wait()則asio::io_service::run()會在瞬間return.
io.run();
return 0;
}
完整的代碼:
#include <iostream>
#include <asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
void print(const asio::error& /*e*/)
{
std::cout << "Hello, world!\n";
}
int main()
{
asio::io_service io;
asio::deadline_timer t(io, boost::posix_time::seconds(5));
t.async_wait(print);
io.run();
return 0;
}
3.4. 回調(diào)函數(shù)的參數(shù)
這里我們將每秒回調(diào)一次,來演示如何回調(diào)函數(shù)參數(shù)的含義
#include <iostream>
#include <asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
首先,調(diào)整一下timer的持續(xù)時間,開始一個異步等待.顯示,回調(diào)函數(shù)需要訪問timer來實(shí)現(xiàn)周期運(yùn)行,所以我們再介紹兩個新參數(shù)
- 指向timer的指針
- 一個int*來指向計數(shù)器
void print(const asio::error& /*e*/,
asio::deadline_timer* t, int* count)
{
我們打算讓這個函數(shù)運(yùn)行6個周期,然而你會發(fā)現(xiàn)這里沒有顯式的方法來終止io_service.不過,回顧上一節(jié),你會發(fā)現(xiàn)當(dāng)asio::io_service::run()會在所有任務(wù)完成時終止.這樣我們當(dāng)計算器的值達(dá)到5時(0為第一次運(yùn)行的值),不再開啟一個新的異步等待就可以了.
if (*count < 5)
{
std::cout << *count << "\n";
++(*count);
然后,我們推遲的timer的終止時間.通過在原先的終止時間上增加延時,我們可以確保timer不會在處理回調(diào)函數(shù)所需時間內(nèi)的到期.
(原文:By calculating the new expiry time relative to the old, we can ensure that the timer does not drift away from the whole-second mark due to any delays in processing the handler.)
t->expires_at(t->expires_at() + boost::posix_time::seconds(1));
然后我們開始一個新的同步等待.如您所見,我們用把print和他的多個參數(shù)用boost::bind函數(shù)合成一個的形為void(const asio::error&)回調(diào)函數(shù)(準(zhǔn)確的說是function object).
在這個例子中, boost::bind的asio::placeholders::error參數(shù)是為了給回調(diào)函數(shù)傳入一個error對象.當(dāng)進(jìn)行一個異步操作,開始boost::bind時,你需要使用它來匹配回調(diào)函數(shù)的參數(shù)表.下一節(jié)中你會學(xué)到回調(diào)函數(shù)不需要error參數(shù)時可以省略它.
t->async_wait(boost::bind(print,
asio::placeholders::error, t, count));
}
}
int main()
{
asio::io_service io;
int count = 0;
asio::deadline_timer t(io, boost::posix_time::seconds(1));
和上面一樣,我們再一次使用了綁定asio::deadline_timer::async_wait()
t.async_wait(boost::bind(print,
asio::placeholders::error, &t, &count));
io.run();
在結(jié)尾,我們打印出的最后一次沒有設(shè)置timer的調(diào)用的count的值
std::cout << "Final count is " << count << "\n";
return 0;
}
完整的代碼:
#include <iostream>
#include <asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
void print(const asio::error& /*e*/,
asio::deadline_timer* t, int* count)
{
if (*count < 5)
{
std::cout << *count << "\n";
++(*count);
t->expires_at(t->expires_at() + boost::posix_time::seconds(1));
t->async_wait(boost::bind(print,
asio::placeholders::error, t, count));
}
}
int main()
{
asio::io_service io;
int count = 0;
asio::deadline_timer t(io, boost::posix_time::seconds(1));
t.async_wait(boost::bind(print,
asio::placeholders::error, &t, &count));
io.run();
std::cout << "Final count is " << count << "\n";
return 0;
}
3.5. 成員函數(shù)作為回調(diào)函數(shù)
本例的運(yùn)行結(jié)果和上一節(jié)類似
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
我們先定義一個printer類
class printer
{
public:
構(gòu)造函數(shù)有一個io_service參數(shù),并且在初始化timer_時用到了它.用來計數(shù)的count_這里同樣作為了成員變量
printer(boost::asio::io_service& io)
: timer_(io, boost::posix_time::seconds(1)),
count_(0)
{
boost::bind同樣可以出色的工作在成員函數(shù)上.眾所周知,所有的非靜態(tài)成員函數(shù)都有一個隱式的this參數(shù),我們需要把this作為參數(shù)bind到成員函數(shù)上.和上一節(jié)類似,我們再次用bind構(gòu)造出void(const boost::asio::error&)形式的函數(shù).
注意,這里沒有指定boost::asio::placeholders::error占位符,因為這個print成員函數(shù)沒有接受一個error對象作為參數(shù).
timer_.async_wait(boost::bind(&printer::print, this));
}
在類的折構(gòu)函數(shù)中我們輸出最后一次回調(diào)的conut的值
~printer()
{
std::cout << "Final count is " << count_ << "\n";
}
print函數(shù)于上一節(jié)的十分類似,但是用成員變量取代了參數(shù).
void print()
{
if (count_ < 5)
{
std::cout << count_ << "\n";
++count_;
timer_.expires_at(timer_.expires_at() + boost::posix_time::seconds(1));
timer_.async_wait(boost::bind(&printer::print, this));
}
}
private:
boost::asio::deadline_timer timer_;
int count_;
};
現(xiàn)在main函數(shù)清爽多了,在運(yùn)行io_service之前只需要簡單的定義一個printer對象.
int main()
{
boost::asio::io_service io;
printer p(io);
io.run();
return 0;
}
完整的代碼:
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
class printer
{
public:
printer(boost::asio::io_service& io)
: timer_(io, boost::posix_time::seconds(1)),
count_(0)
{
timer_.async_wait(boost::bind(&printer::print, this));
}
~printer()
{
std::cout << "Final count is " << count_ << "\n";
}
void print()
{
if (count_ < 5)
{
std::cout << count_ << "\n";
++count_;
timer_.expires_at(timer_.expires_at() + boost::posix_time::seconds(1));
timer_.async_wait(boost::bind(&printer::print, this));
}
}
private:
boost::asio::deadline_timer timer_;
int count_;
};
int main()
{
boost::asio::io_service io;
printer p(io);
io.run();
return 0;
}
3.6. 多線程回調(diào)同步
本節(jié)演示了使用boost::asio::strand在多線程程序中進(jìn)行回調(diào)同步(synchronise).
先前的幾節(jié)闡明了如何在單線程程序中用boost::asio::io_service::run()進(jìn)行同步.如您所見,asio庫確保 僅當(dāng) 當(dāng)前線程調(diào)用boost::asio::io_service::run()時產(chǎn)生回調(diào).顯然,僅在一個線程中調(diào)用boost::asio::io_service::run() 來確保回調(diào)是適用于并發(fā)編程的.
一個基于asio的程序最好是從單線程入手,但是單線程有如下的限制,這一點(diǎn)在服務(wù)器上尤其明顯:
- 當(dāng)回調(diào)耗時較長時,反應(yīng)遲鈍.
- 在多核的系統(tǒng)上無能為力
如果你發(fā)覺你陷入了這種困擾,可以替代的方法是建立一個boost::asio::io_service::run()的線程池.然而這樣就允許回調(diào)函數(shù)并發(fā)執(zhí)行.所以,當(dāng)回調(diào)函數(shù)需要訪問一個共享,線程不安全的資源時,我們需要一種方式來同步操作.
#include <iostream>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
在上一節(jié)的基礎(chǔ)上我們定義一個printer類,此次,它將并行運(yùn)行兩個timer
class printer
{
public:
除了聲明了一對boost::asio::deadline_timer,構(gòu)造函數(shù)也初始化了類型為boost::asio::strand的strand_成員.
boost::asio::strand可以分配的回調(diào)函數(shù).它保證無論有多少線程調(diào)用了boost::asio::io_service::run(),下一個回調(diào)函數(shù)僅在前一個回調(diào)函數(shù)完成后開始,當(dāng)然回調(diào)函數(shù)仍然可以和那些不使用boost::asio::strand分配,或是使用另一個boost::asio::strand分配的回調(diào)函數(shù)一起并發(fā)執(zhí)行.
printer(boost::asio::io_service& io)
: strand_(io),
timer1_(io, boost::posix_time::seconds(1)),
timer2_(io, boost::posix_time::seconds(1)),
count_(0)
{
當(dāng)一個異步操作開始時,用boost::asio::strand來 "wrapped(包裝)"回調(diào)函數(shù).boost::asio::strand::wrap()會返回一個由boost::asio::strand分配的新的handler(句柄),這樣,我們可以確保它們不會同時運(yùn)行.
timer1_.async_wait(strand_.wrap(boost::bind(&printer::print1, this)));
timer2_.async_wait(strand_.wrap(boost::bind(&printer::print2, this)));
}
~printer()
{
std::cout << "Final count is " << count_ << "\n";
}
多線程程序中,回調(diào)函數(shù)在訪問共享資源前需要同步.這里共享資源是std::cout 和count_變量.
void print1()
{
if (count_ < 10)
{
std::cout << "Timer 1: " << count_ << "\n";
++count_;
timer1_.expires_at(timer1_.expires_at() + boost::posix_time::seconds(1));
timer1_.async_wait(strand_.wrap(boost::bind(&printer::print1, this)));
}
}
void print2()
{
if (count_ < 10)
{
std::cout << "Timer 2: " << count_ << "\n";
++count_;
timer2_.expires_at(timer2_.expires_at() + boost::posix_time::seconds(1));
timer2_.async_wait(strand_.wrap(boost::bind(&printer::print2, this)));
}
}
private:
boost::asio::strand strand_;
boost::asio::deadline_timer timer1_;
boost::asio::deadline_timer timer2_;
int count_;
};
main函數(shù)中boost::asio::io_service::run()在兩個線程中被調(diào)用:主線程,一個boost::thread線程.
正如單線程中那樣,并發(fā)的boost::asio::io_service::run()會一直運(yùn)行直到完成任務(wù).后臺的線程將在所有異步線程完成后終結(jié).
int main()
{
boost::asio::io_service io;
printer p(io);
boost::thread t(boost::bind(&boost::asio::io_service::run, &io));
io.run();
t.join();
return 0;
}
完整的代碼:
#include <iostream>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
class printer
{
public:
printer(boost::asio::io_service& io)
: strand_(io),
timer1_(io, boost::posix_time::seconds(1)),
timer2_(io, boost::posix_time::seconds(1)),
count_(0)
{
timer1_.async_wait(strand_.wrap(boost::bind(&printer::print1, this)));
timer2_.async_wait(strand_.wrap(boost::bind(&printer::print2, this)));
}
~printer()
{
std::cout << "Final count is " << count_ << "\n";
}
void print1()
{
if (count_ < 10)
{
std::cout << "Timer 1: " << count_ << "\n";
++count_;
timer1_.expires_at(timer1_.expires_at() + boost::posix_time::seconds(1));
timer1_.async_wait(strand_.wrap(boost::bind(&printer::print1, this)));
}
}
void print2()
{
if (count_ < 10)
{
std::cout << "Timer 2: " << count_ << "\n";
++count_;
timer2_.expires_at(timer2_.expires_at() + boost::posix_time::seconds(1));
timer2_.async_wait(strand_.wrap(boost::bind(&printer::print2, this)));
}
}
private:
boost::asio::strand strand_;
boost::asio::deadline_timer timer1_;
boost::asio::deadline_timer timer2_;
int count_;
};
int main()
{
boost::asio::io_service io;
printer p(io);
boost::thread t(boost::bind(&boost::asio::io_service::run, &io));
io.run();
t.join();
return 0;
}
3.7. TCP客戶端:對準(zhǔn)時間
#include <iostream>
#include <boost/array.hpp>
#include <boost/asio.hpp>
本程序的目的是訪問一個時間同步服務(wù)器,我們需要用戶指定一個服務(wù)器(如time-nw.nist.gov),用IP亦可.
(譯者注:日期查詢協(xié)議,這種時間傳輸協(xié)議不指定固定的傳輸格式,只要求按照ASCII標(biāo)準(zhǔn)發(fā)送數(shù)據(jù)。)
using boost::asio::ip::tcp;
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: client <host>" << std::endl;
return 1;
}
用asio進(jìn)行網(wǎng)絡(luò)連接至少需要一個boost::asio::io_service對象
boost::asio::io_service io_service;
我們需要把在命令行參數(shù)中指定的服務(wù)器轉(zhuǎn)換為TCP上的節(jié)點(diǎn).完成這項工作需要boost::asio::ip::tcp::resolver對象
tcp::resolver resolver(io_service);
一個resolver對象查詢一個參數(shù),并將其轉(zhuǎn)換為TCP上節(jié)點(diǎn)的列表.這里我們把a(bǔ)rgv[1]中的sever的名字和要查詢字串daytime關(guān)聯(lián).
tcp::resolver::query query(argv[1], "daytime");
節(jié)點(diǎn)列表可以用 boost::asio::ip::tcp::resolver::iterator 來進(jìn)行迭代.iterator默認(rèn)的構(gòu)造函數(shù)生成一個end iterator.
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
tcp::resolver::iterator end;
現(xiàn)在我們建立一個連接的sockert,由于獲得節(jié)點(diǎn)既有IPv4也有IPv6的.所以,我們需要依次嘗試他們直到找到一個可以正常工作的.這步使得我們的程序獨(dú)立于IP版本
tcp::socket socket(io_service);
boost::asio::error error = boost::asio::error::host_not_found;
while (error && endpoint_iterator != end)
{
socket.close();
socket.connect(*endpoint_iterator++, boost::asio::assign_error(error));
}
if (error)
throw error;
連接完成,我們需要做的是讀取daytime服務(wù)器的響應(yīng).
我們用boost::array來保存得到的數(shù)據(jù),boost::asio::buffer()會自動根據(jù)array的大小暫停工作,來防止緩沖溢出.除了使用boost::array,也可以使用char [] 或std::vector.
for (;;)
{
boost::array<char, 128> buf;
boost::asio::error error;
size_t len = socket.read_some(
boost::asio::buffer(buf), boost::asio::assign_error(error));
當(dāng)服務(wù)器關(guān)閉連接時,boost::asio::ip::tcp::socket::read_some()會用boost::asio::error::eof標(biāo)志完成, 這時我們應(yīng)該退出讀取循環(huán)了.
if (error == boost::asio::error::eof)
break; // Connection closed cleanly by peer.
else if (error)
throw error; // Some other error.
std::cout.write(buf.data(), len);
}
如果發(fā)生了什么異常我們同樣會拋出它
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
運(yùn)行示例:在windowsXP的cmd窗口下
輸入:upload.exe time-a.nist.gov
輸出:54031 06-10-23 01:50:45 07 0 0 454.2 UTC(NIST) *
完整的代碼:
#include <iostream>
#include <boost/array.hpp>
#include <asio.hpp>
using asio::ip::tcp;
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: client <host>" << std::endl;
return 1;
}
asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::query query(argv[1], "daytime");
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
tcp::resolver::iterator end;
tcp::socket socket(io_service);
asio::error error = asio::error::host_not_found;
while (error && endpoint_iterator != end)
{
socket.close();
socket.connect(*endpoint_iterator++, asio::assign_error(error));
}
if (error)
throw error;
for (;;)
{
boost::array<char, 128> buf;
asio::error error;
size_t len = socket.read_some(
asio::buffer(buf), asio::assign_error(error));
if (error == asio::error::eof)
break; // Connection closed cleanly by peer.
else if (error)
throw error; // Some other error.
std::cout.write(buf.data(), len);
}
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
3.8. TCP同步時間服務(wù)器
#include <ctime>
#include <iostream>
#include <string>
#include <asio.hpp>
using asio::ip::tcp;
我們先定義一個函數(shù)返回當(dāng)前的時間的string形式.這個函數(shù)會在我們所有的時間服務(wù)器示例上被使用.
std::string make_daytime_string()
{
using namespace std; // For time_t, time and ctime;
time_t now = time(0);
return ctime(&now);
}
int main()
{
try
{
asio::io_service io_service;
新建一個asio::ip::tcp::acceptor對象來監(jiān)聽新的連接.我們監(jiān)聽TCP端口13,IP版本為V4
tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), 13));
這是一個iterative server,也就是說同一時間只能處理一個連接.建立一個socket來表示一個和客戶端的連接, 然后等待客戶端的連接.
for (;;)
{
tcp::socket socket(io_service);
acceptor.accept(socket);
當(dāng)客戶端訪問服務(wù)器時,我們獲取當(dāng)前時間,然后返回它.
std::string message = make_daytime_string();
asio::write(socket, asio::buffer(message),
asio::transfer_all(), asio::ignore_error());
}
}
最后處理異常
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
運(yùn)行示例:運(yùn)行服務(wù)器,然后運(yùn)行上一節(jié)的客戶端,在windowsXP的cmd窗口下
輸入:client.exe 127.0.0.1
輸出:Mon Oct 23 09:44:48 2006
完整的代碼:
#include <ctime>
#include <iostream>
#include <string>
#include <asio.hpp>
using asio::ip::tcp;
std::string make_daytime_string()
{
using namespace std; // For time_t, time and ctime;
time_t now = time(0);
return ctime(&now);
}
int main()
{
try
{
asio::io_service io_service;
tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), 13));
for (;;)
{
tcp::socket socket(io_service);
acceptor.accept(socket);
std::string message = make_daytime_string();
asio::write(socket, asio::buffer(message),
asio::transfer_all(), asio::ignore_error());
}
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}