#include #include #include #include #include #include #include #include #include using namespace boost; using boost::asio::ip::tcp; using boost::system::error_code; typedef array CharArrayT; void send(); void receive(int numBufs); asio::io_service iosvc; tcp::socket sock(iosvc); const size_t tcp_buf_size = 64*1024; const tcp::endpoint endpoint(asio::ip::address::from_string("127.0.0.1"), 2345); // arbitrary port inline char next_char() { return (char)rand(); } int main(int argc, char *argv[]) try { // Seed RNG with fixed value to ensure same sequence on send & receive srand(12345); if (argc == 2 && strcmp("send", argv[1]) == 0) send(); else if (argc == 3 && strcmp("receive", argv[1]) == 0) receive(atoi(argv[2])); else std::cerr << "Usage: " << argv[0] << " ( send | receive )\n"; } catch (const std::exception &e) { std::cerr << "Exception: " << e.what() << '\n'; } void send() { CharArrayT store; sock.open(endpoint.protocol()); asio::socket_base::send_buffer_size option(tcp_buf_size); sock.set_option(option); sock.connect(endpoint); for (error_code ec; !ec; ) { std::generate(store.begin(), store.end(), &next_char); write(sock, asio::buffer(store), asio::transfer_all(), ec); } } void handler(const error_code &ec, size_t bytes_transferred, shared_ptr buf) { if (ec) return; for (size_t i = 0; i < bytes_transferred; ++i) { if ((*buf)[i] != next_char()) { std::cerr << "Streams differ\n"; exit(1); } } sock.async_read_some(asio::buffer(*buf), bind(&handler, _1, _2, buf)); } void receive(int numBufs) { tcp::acceptor acceptor(iosvc, endpoint); asio::socket_base::receive_buffer_size option(tcp_buf_size); acceptor.set_option(option); acceptor.accept(sock); for (int i = 0; i < numBufs; ++i) { shared_ptr buf(new CharArrayT); sock.async_read_some(asio::buffer(*buf), bind(&handler, _1, _2, buf)); } iosvc.run(); }