-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathExample3_LinuxOnly.cpp
More file actions
66 lines (50 loc) · 2.03 KB
/
Example3_LinuxOnly.cpp
File metadata and controls
66 lines (50 loc) · 2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <boost/asio.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/array.hpp>
#include <boost/make_shared.hpp>
#include "asio_helper.hpp"
int main()
{
namespace asio = boost::asio;
asio::io_service io;
// Turn off newline buffering
::termios term;
::tcgetattr( STDIN_FILENO, &term );
term.c_lflag &= ~(ICANON);
::tcsetattr( STDIN_FILENO, TCSANOW, &term );
asio::posix::stream_descriptor in( io, ::dup( STDIN_FILENO ) );
asio::posix::stream_descriptor out( io, ::dup( STDOUT_FILENO ) );
using namespace asio_helper::handlers;
asio_helper::do_async(io,[&io,&in,&out](asio_helper::async_helper helper){
// Declare the error_code we will be using
boost::system::error_code ec;
// Write the prompt
std::tie(ec,std::ignore) = helper.await_async_write(out,asio::buffer( "Please type in your name: " ));
// Prepare the buffer to receive no more than 10 characters
const std::size_t bufferSize = 10;
boost::asio::streambuf response( bufferSize );
response.prepare( bufferSize );
// Read until a newline
std::tie(ec,std::ignore) = helper.await_async_read_until(in,response,'\n');
if( ec )
{
// If the name is too long, print out a prompt
if( ec == asio::error::not_found ) {
std::tie(ec,std::ignore) = helper.await_async_write(out,asio::buffer( "\nYour name is too long, try a nickname\n" ));
}
else {
auto message = std::string("Error: ") + ec.message() + "\n" ;
std::tie(ec,std::ignore) = helper.await_async_write(out,asio::buffer( message ));
}
}
else
{
std::istream is( &response);
std::string name;
std::getline( is, name, '\n' );
auto message = "Hello " + name + "!\n" ;
helper.await_async_write(out,asio::buffer( message ));
}
});
io.run();
}