boost::asio中的C/S同步实例源码

时间:2022-09-08 23:22:18

近来*地研究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:6688
ip::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;
}

运行细节:

boost::asio中的C/S同步实例源码

boost::asio中的C/S同步实例源码

注意所有的源码均在Ubuntu 14.04 64bit上运行测试, 比参考文献[1]中更详细更具体.


参考文献:

[1].罗剑锋, Boost程序库完全开发指南---深入C++"准"标准库