Created
November 2, 2018 15:54
-
-
Save varphone/7f3233e42b267485d077f92fd0c8c9e5 to your computer and use it in GitHub Desktop.
reactor-file-async-read.cc
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 <boost/asio.hpp> | |
#include <boost/system/error_code.hpp> | |
#include <iostream> | |
#include <memory> | |
#include <string> | |
// Import function and types or define alias. | |
using boost::asio::buffer; | |
using boost::asio::null_buffers; | |
using ErrorCode = boost::system::error_code; | |
using IoContext = boost::asio::io_context; | |
using PosixStream = boost::asio::posix::stream_descriptor; | |
using PosixStreamPtr = std::shared_ptr<PosixStream>; | |
// The module scope stream pointer. | |
static PosixStreamPtr stream; | |
// Callback for read ready. | |
static void read_ready(ErrorCode const &e, size_t s) | |
{ | |
if (!e) | |
{ | |
char buf[1024]; | |
// Actual read the data to buffer. | |
size_t n = stream->read_some(buffer(buf, sizeof(buf))); | |
// Process the readed data, like print out, etc. | |
std::cout << "Buffer: [" << std::string(buf, n) << "]\n"; | |
// Wait for next read ready. | |
stream->async_read_some(null_buffers(), read_ready); | |
} | |
} | |
int main(int argc, char **argv) | |
{ | |
IoContext io; | |
// Create a posix stream via stdin file descriptor. | |
stream = std::move(std::make_shared<PosixStream>(io, STDIN_FILENO)); | |
// Enable nonblocking access. | |
stream->non_blocking(true); | |
// Wait for read ready. | |
stream->async_read_some(null_buffers(), read_ready); | |
// Running the io. | |
io.run(); | |
// Exited from the io loop. | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment