server.cpp
#include <iostream>
#include <boost/asio.hpp>
using namespace boost::asio;
int main()
try {
io_service ios;
ip::address addr;
addr = addr.from_string("127.0.0.1");
std::cout << "server starting." << std::endl;
ip::tcp::acceptor acceptor(ios, ip::tcp::endpoint(addr, 6688));
std::cout << acceptor.local_endpoint().address() << ":" << acceptor.local_endpoint().port() << std::endl;
while (true) {
std::cout<<"socket wait"<<std::endl;
ip::tcp::socket sock(ios);
acceptor.accept(sock);
std::cout << "client: " << sock.remote_endpoint().address()<<":" <<sock.remote_endpoint().port()<< std::endl;
sock.write_some(buffer("hello asio"));
}
} catch (std::exception& e) {
std::cout << e.what() << std::endl;
}
client.cpp
#include <iostream>
#include <boost/ref.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
using namespace boost::asio;
using namespace std;
void client(io_service &ios)
try {
std::cout << "client starting." << std::endl;
ip::tcp::socket sock(ios);
ip::address adr = ip::address::from_string("127.0.0.1");
std::cout << adr.to_string() << std::endl;
ip::tcp::endpoint ep(adr, 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 timer;
public:
template<typename F>
a_timer(io_service &ios, int x, F func) : f(func), count_max(x), count(0),
timer(ios, boost::posix_time::millisec(500)) {
timer.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();
timer.expires_at(timer.expires_at() + boost::posix_time::millisec(500));
timer.async_wait(boost::bind(&a_timer::call_func, this, boost::asio::placeholders::error));
}
};
int main() {
io_service ios;
//自定义定时器5次执行client()函数
a_timer at(ios, 5, boost::bind(client, boost::ref(ios)));
ios.run();
}