| 21 | using asio::ip::tcp; |
| 22 | |
| 23 | void start(asio::io_context& io_context, std::string host, std::string port) { |
| 24 | auto [ec, socket] = connect(io_context, host, port); |
| 25 | if (ec) { |
| 26 | std::cout << "Connect error: " << ec.message() << '\n'; |
| 27 | throw asio::system_error(ec); |
| 28 | } |
| 29 | std::cout << "Connect to " << host << ":" << port << " successfully.\n"; |
| 30 | const int max_length = 1024; |
| 31 | char write_buf[max_length] = {"hello async_simple"}; |
| 32 | char read_buf[max_length]; |
| 33 | const int count = 10000; |
| 34 | for (int i = 0; i < count; ++i) { |
| 35 | write(socket, asio::buffer(write_buf, max_length)); |
| 36 | auto [error, reply_length] = |
| 37 | read_some(socket, asio::buffer(read_buf, max_length)); |
| 38 | if (error == asio::error::eof) { |
| 39 | std::cout << "eof at message index: " << i << '\n'; |
| 40 | break; |
| 41 | } else if (error) { |
| 42 | std::cout << "error: " << error.message() |
| 43 | << ", message index: " << i << '\n'; |
| 44 | throw asio::system_error(error); |
| 45 | } |
| 46 | |
| 47 | // handle read data as your wish. |
| 48 | } |
| 49 | |
| 50 | std::cout << "Finished send and receive " << count |
| 51 | << " messages, client will close.\n"; |
| 52 | std::error_code ignore_ec; |
| 53 | socket.shutdown(asio::ip::tcp::socket::shutdown_both, ignore_ec); |
| 54 | socket.close(ignore_ec); |
| 55 | } |
| 56 | |
| 57 | int main(int argc, char* argv[]) { |
| 58 | try { |