Skip to content

Instantly share code, notes, and snippets.

@ratatosk
Last active December 11, 2015 21:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ratatosk/4665157 to your computer and use it in GitHub Desktop.
Save ratatosk/4665157 to your computer and use it in GitHub Desktop.
#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);
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);
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::streambuf b;
boost::asio::read_until(sock, b, '\n');
std::istream is(&b);
std::string line;
std::getline(is, line);
std::cout << "Answer: " << line << std::endl;
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::streambuf b;
boost::asio::read_until(sock, b, '\n');
std::istream is(&b);
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