Skip to content

Instantly share code, notes, and snippets.

@ratatosk
Created January 29, 2013 15:51
Show Gist options
  • Save ratatosk/4665257 to your computer and use it in GitHub Desktop.
Save ratatosk/4665257 to your computer and use it in GitHub Desktop.
#include <stdexcept>
#include <iostream>
#include <string>
#include <boost/thread.hpp>
#include <boost/asio.hpp>
#include <boost/chrono.hpp>
using boost::asio::ip::tcp;
boost::asio::io_service io;
tcp::socket sock(io);
boost::asio::streambuf buf;
void cln_handle_read(const boost::system::error_code& e, std::size_t) {
if (e) {
throw std::runtime_error(e.message());
}
std::istream is(&buf);
std::string line;
std::getline(is, line);
std::cout << "Answer: " << line << std::endl;
}
int client() {
try {
std::string data("Henrich Herz");
tcp::resolver resolver(io);
tcp::resolver::query query(tcp::v4(), "localhost", "12345");
tcp::resolver::iterator iterator = resolver.resolve(query);
tcp::socket s(io);
boost::asio::connect(sock, iterator);
boost::asio::write(sock, boost::asio::buffer(data));
boost::asio::write(sock, boost::asio::buffer("\n"));
boost::this_thread::sleep_for(boost::chrono::seconds(1));
boost::asio::async_read_until(sock, buf, '\n', &cln_handle_read);
io.run();
return 0;
} catch (const std::exception &e) {
std::cout << "client fail: " << e.what() << std::endl;
return 1;
}
}
int server() {
try {
tcp::acceptor acc(io, tcp::endpoint(tcp::v4(), 12345));
acc.accept(sock);
boost::asio::read_until(sock, buf, '\n');
std::istream is(&buf);
std::string line;
std::getline(is, line);
boost::asio::write(sock, boost::asio::buffer(line));
boost::asio::write(sock, boost::asio::buffer("\n"));
return 0;
} catch (const std::exception &e) {
std::cout << "server fail: " << e.what() << std::endl;
return 1;
}
}
int main(int argc, char **argv) {
if (argc == 2 && std::string("client") == argv[1]) {
return client();
} else if (argc == 2 && std::string("server") == argv[1]) {
return server();
} else {
std::cout << "wrong usage\n";
return 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment