boost::asio中的C/S同步实例源码
生活随笔
收集整理的這篇文章主要介紹了
boost::asio中的C/S同步实例源码
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
近來狂熱地研究boost的開發技術,現將讀書筆記整理如下:
需要說明的是, 本博該專題下面關于boost的源碼是采用boost1.55版本, 運行在Ubuntu 14.04 64bit下面, 使用apt包安裝(非源碼編譯安裝), 后續不再做說明.
同步socket類型的服務器源碼實現:
//g++ -g sync_tcp_server.cpp -o sync_tcp_server -lboost_system
//#include <iostream>
#include <boost/asio.hpp>
#include <boost/system/error_code.hpp>using namespace std;
using namespace boost::asio;int main(){try{cout << "sync tcp server start ......" << endl;io_service ios;//server listen at 127.0.0.1:6688ip::tcp::acceptor acceptor(ios, ip::tcp::endpoint(ip::tcp::v4(), 6688));cout << acceptor.local_endpoint().address() << endl;while(true){ip::tcp::socket sock(ios);acceptor.accept(sock);cout << "client: ";cout << sock.remote_endpoint().address() << endl;sock.write_some(buffer("hello asio"));}}catch(std::exception& e){cout << e.what() << endl;}
}
同步socket類型的客戶端源碼實現:
//g++ -g sync_tcp_client.cpp -o sync_tcp_client -lboost_system -lboost_date_time
//#include <iostream>
#include <boost/ref.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>using namespace boost::asio;void client(io_service &ios){try {std::cout << "sync client starting ......" << std::endl;ip::tcp::socket sock(ios);ip::tcp::endpoint ep(ip::address::from_string("127.0.0.1"), 6688);sock.connect(ep);std::vector<char> str(100, 0);sock.read_some(buffer(str));std::cout << "receive from: " << sock.remote_endpoint().address() << std::endl;std::cout << &str[0] << std::endl;} catch (std::exception &e) {std::cout << e.what() << std::endl;}
}class a_timer
{private:int count, count_max;boost::function<void()> f;boost::asio::deadline_timer t;public:template<typename F>a_timer(io_service &ios, int x, F func): f(func), count_max(x), count(0),t(ios, boost::posix_time::millisec(500)) {t.async_wait(boost::bind(&a_timer::call_func, this, boost::asio::placeholders::error));}void call_func(const boost::system::error_code&){if (count >= count_max) {return;}++count;f();t.expires_at(t.expires_at() + boost::posix_time::millisec(500));t.async_wait(boost::bind(&a_timer::call_func, this, boost::asio::placeholders::error));}};int main()
{io_service ios;a_timer at(ios, 5, boost::bind(client, boost::ref(ios)));ios.run();return 0;
}
運行細節:
注意所有的源碼均在Ubuntu 14.04 64bit上運行測試, 比參考文獻[1]中更詳細更具體.
參考文獻:
[1].羅劍鋒, Boost程序庫完全開發指南---深入C++"準"標準庫
總結
以上是生活随笔為你收集整理的boost::asio中的C/S同步实例源码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 递归遍历Linux下的目录文件源码实现
- 下一篇: boost::asio异步模式的C/S客