Created
August 23, 2011 07:35
-
-
Save erikfrey/1164576 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <cstdlib> | |
| #include <cstring> | |
| #include <iostream> | |
| #include <boost/array.hpp> | |
| #include <boost/bind.hpp> | |
| #include <boost/asio.hpp> | |
| namespace posix = boost::asio::posix; | |
| class echo_client | |
| { | |
| public: | |
| echo_client(boost::asio::io_service& io_service) | |
| : input_(io_service, STDIN_FILENO), | |
| output_(io_service, STDOUT_FILENO), | |
| input_buffer_(1024) | |
| { | |
| // Read a line of input entered by the user. | |
| boost::asio::async_read_until(input_, input_buffer_, '\n', | |
| boost::bind(&echo_client::handle_read, this, | |
| boost::asio::placeholders::error, | |
| boost::asio::placeholders::bytes_transferred)); | |
| } | |
| private: | |
| void handle_read(const boost::system::error_code& error, | |
| std::size_t length) | |
| { | |
| if (!error) | |
| { | |
| // Write the message to the output | |
| boost::asio::async_write(output_, input_buffer_, | |
| boost::bind(&echo_client::handle_write, this, | |
| boost::asio::placeholders::error)); | |
| } | |
| else | |
| { | |
| close(); | |
| } | |
| } | |
| void handle_write(const boost::system::error_code& error) | |
| { | |
| if (!error) | |
| { | |
| // Read a line of input entered by the user. | |
| boost::asio::async_read_until(input_, input_buffer_, '\n', | |
| boost::bind(&echo_client::handle_read, this, | |
| boost::asio::placeholders::error, | |
| boost::asio::placeholders::bytes_transferred)); | |
| } | |
| else | |
| { | |
| close(); | |
| } | |
| } | |
| void close() | |
| { | |
| // Cancel all outstanding asynchronous operations. | |
| input_.close(); | |
| output_.close(); | |
| } | |
| private: | |
| posix::stream_descriptor input_; | |
| posix::stream_descriptor output_; | |
| boost::asio::streambuf input_buffer_; | |
| }; | |
| int main(int argc, char* argv[]) | |
| { | |
| try | |
| { | |
| boost::asio::io_service io_service; | |
| echo_client c(io_service); | |
| io_service.run(); | |
| } | |
| catch (std::exception& e) | |
| { | |
| std::cerr << "Exception: " << e.what() << "\n"; | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment