Server // blocking_server.cpp // #include "stdafx.h" #include "blocking_server.h" #include <boost/asio.hpp> #include <boost/shared_ptr.hpp> #include <boost/thread.hpp> #include <boost/bind.hpp> #include <boost/lexical_cast.hpp> #include <sstream> using namespace std; using boost::asio::ip::tcp; typedef boost::shared_ptr<tcp::socket> socket_ptr; void send_data(socket_ptr sock) { // can not do this in async mode, // for(...){ async_write(...) } for(int i = 1; i <= 100; i++) { string str = boost::lexical_cast<string>(i) + "/n"; boost::asio::write(*sock, boost::asio::buffer(str)); cout << "send data: " << str << endl; boost::this_thread::sleep(boost::posix_time::seconds(1)); } boost::asio::write(*sock, boost::asio::buffer("done/n")); cout << "send done. " << endl; } void start_session(socket_ptr sock) { try { cout << "accept a new connection. " << endl; boost::asio::streambuf abuf; size_t count = boost::asio::read_until(*sock, abuf, '/n'); istream is(&abuf); string line; std::getline(is, line); if(line == "request_data") { cout << "receive request, sending data." << endl; send_data(sock); } } catch (std::exception &e) { cout << "Exception in session: " << e.what() << endl; } } void start_server(boost::asio::io_service &ios, short port) { tcp::acceptor a(ios, tcp::endpoint(tcp::v4(), port)); cout << "start server, port = " << port << endl; for(;;) { socket_ptr sock(new tcp::socket(ios)); a.accept(*sock); boost::thread t(boost::bind(start_session, sock)); } } int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) { int nRetCode = 0; try { boost::asio::io_service ios; start_server(ios, 12345); } catch(std::exception &e) { cout << "Exception in main: " << e.what() << endl; } return nRetCode; } Client // blocking_client.cpp // #include "stdafx.h" #include "blocking_client.h" #include <boost/asio.hpp> #include <boost/thread.hpp> #include <boost/bind.hpp> #include <iostream> using namespace std; using namespace boost::asio; using boost::asio::ip::tcp; void handle_data(string data) { cout << "get " << data << endl; } void start_connection(string ip, short port) { boost::asio::io_service ios; tcp::socket client(ios); tcp::endpoint ep(ip::address_v4::from_string(ip), port); boost::system::error_code ec; client.connect(ep, ec); if(ec) { cout << "fail to connect " << ip << ":" << port << endl; return; } boost::asio::streambuf abuf; istream is(&abuf); boost::asio::write(client, boost::asio::buffer("request_data/n")); while(true) { boost::system::error_code ec; size_t count = boost::asio::read_until(client, abuf, '/n', ec); if(ec) { //cout << "read error." << endl; } else { string line; std::getline(is, line); handle_data(line); } } } int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) { int nRetCode = 0; boost::thread t(boost::bind(start_connection, "127.0.0.1", 12345)); t.join(); system("pause"); return nRetCode; } end.