Skip to content

Instantly share code, notes, and snippets.

@celeron633
Last active January 3, 2021 08:24
Show Gist options
  • Save celeron633/3acc26cb76a43d85c5447077d9021cbc to your computer and use it in GitHub Desktop.
Save celeron633/3acc26cb76a43d85c5447077d9021cbc to your computer and use it in GitHub Desktop.
boost::asio async tcp client demo
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
using namespace std;
using namespace boost::asio;
using namespace boost::placeholders;
class Client {
private:
io_service& ios;
ip::tcp::endpoint _ep;
ip::tcp::socket socket;
char buf[1024];
public:
Client(io_service& io, const ip::tcp::endpoint& ep) : ios(io), _ep(ep), socket(io){
do_connect();
}
~Client() {
socket.close();
}
void do_connect() {
cout << "connecting to " << _ep.address().to_string() << endl;
socket.async_connect(_ep, bind(&Client::handle_connect, this, _1));
}
void handle_connect(const boost::system::error_code& ec) {
if (ec) {
std::cout << ec.message() << std::endl;
return;
};
cout << "connected to " << _ep.address().to_string() << endl;
boost::asio::async_read(socket, buffer(this->buf, 10), boost::bind(&Client::handle_read, this, _1));
}
void handle_read(const boost::system::error_code& ec) {
if (ec) {
std::cout << ec.message() << std::endl;
return;
};
for (auto i = 0; i < 10; i++) {
printf_s("0x%x ", buf[i]);
}
std::cout << std::endl;
boost::asio::async_read(socket, buffer(this->buf, 10), boost::bind(&Client::handle_read, this, _1));
}
};
void run_client_service(std::string& ipAddr, int port) {
cout << "client start ......" << endl;
io_service ios;
ip::tcp::endpoint ep;
ep.address(ip::address::from_string(ipAddr));
ep.port(port);
Client client(ios, ep);
boost::thread(boost::bind(&boost::asio::io_service::run, boost::ref(ios)));
ios.run();
}
int main(int argc, char* argv[])
{
std::string addr;
int port;
try {
std::cout << "enter address:";
std::cin >> addr;
std::cout << "enter port:";
std::cin >> port;
boost::thread work_thread(boost::bind(&run_client_service, addr, port));
work_thread.join();
return 0;
} catch (exception& e) {
std::cout << e.what() << std::endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment